买卖股票的最佳时机 II LeetCode-122

  func maxProfit(prices []int) int {
    max:=0
    for i:=1;i<len(prices);i++{
        if prices[i]>prices[i-1]{
            max+=prices[i]-prices[i-1]
        }
    }
    return max
}

下面这个有点不好ai

func maxProfit(prices []int) int {
    length := len(prices)
    if length < 2 {
        return 0
    }
    dp := make([][2]int, length)

    dp[0][0] = 0            //如果什么都不做,dp[0][0] = 0;
    dp[0][1] = -prices[0]      //如果买入股票,当前收益是负数

    for i := 1; i < length; i++ {
        dp[i][0] = max(dp[i-1][0], dp[i-1][1]+prices[i])
        dp[i][1] = max(dp[i-1][1], dp[i-1][0]-prices[i])      //终止时候,输出 dp[len - 1][0],因一定有 dp[len - 1][0](卖了未持股) > dp[len - 1][1](持股)。
    }

    return dp[length-1][0]

}

func max(x, y int) int {
    if x > y {
        return x
    }
    return y
}
posted @ 2020-07-27 18:31  柠檬橘  阅读(108)  评论(0编辑  收藏  举报