代码动态规划:
- 某一天中,你会处于 5 种状态,
- 一:什么也没干
- 二:一次买入
- 三:一次买入卖出
- 四:再次买入
- 五:再次卖出
第一种状态永远是 0 ,自然可以不考虑
每种状态都可以继承昨天的自己或者由买入卖出状态转换
代码中不需要考虑是否当天买入卖出,因为这项操作带来的收益是 0 ,也就是说不会影响最终结果
func maxProfit(prices []int) int {
buy1, sell1 := -prices[0], 0
buy2, sell2 := -prices[0], 0
for i := 1; i < len(prices); i++ {
buy1 = max(buy1, -prices[i])
sell1 = max(sell1, buy1+prices[i])
buy2 = max(buy2, sell1-prices[i])
sell2 = max(sell2, buy2+prices[i])
}
return sell2
}
func max(a, b int) int {
if a > b {
return a
}
return b
}