买卖股票的最佳时机——动态规划

97 阅读1分钟

image.png

代码动态规划:

  1. 某一天中,你会处于 5 种状态,
  2. 一:什么也没干
  3. 二:一次买入
  4. 三:一次买入卖出
  5. 四:再次买入
  6. 五:再次卖出

第一种状态永远是 0 ,自然可以不考虑
每种状态都可以继承昨天的自己或者由买入卖出状态转换

代码中不需要考虑是否当天买入卖出,因为这项操作带来的收益是 0 ,也就是说不会影响最终结果

image.png

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
}