Skip to content

Instantly share code, notes, and snippets.

@fengyitsai
Created December 18, 2019 17:56
Show Gist options
  • Save fengyitsai/c79e83637c60d68e5420255443fea1c2 to your computer and use it in GitHub Desktop.
Save fengyitsai/c79e83637c60d68e5420255443fea1c2 to your computer and use it in GitHub Desktop.
309. Best Time to Buy and Sell Stock with Cooldown
class Solution {
func maxProfit(_ prices: [Int]) -> Int {
guard !prices.isEmpty else {
return 0
}
var hold = [Int](repeating: Int.min, count: prices.count + 1)
var sell = [Int](repeating: 0, count: prices.count + 1)
var cooldown = [Int](repeating: 0, count: prices.count + 1)
for day in 1...prices.count {
hold[day] = max(hold[day-1], cooldown[day-1] - prices[day-1])
sell[day] = hold[day-1] + prices[day-1]
cooldown[day] = max(cooldown[day-1],sell[day-1])
}
return max(cooldown[prices.count],hold[prices.count],sell[prices.count])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment