剑指 Offer 63. 股票的最大利润

281 阅读1分钟

题目:
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/be… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法:
每天可能有这么几个状态
0:啥也不操作
buy1:买入了一次
sell1:卖了一次
buy2:买了2次
sell2:卖了2次

最大利润:

buy1=max(buy1', -prices[i]) // 前一天第一次买入,今天不操作/今天第一次买入
sell1=max(sell1', buy1' + prices[i]) // 前一天第一次卖出,今天不操作/今天第一次卖出
buy2=max(buy2', sell1'-prices[i])// 前一天第二次买入,今天不操作/今天第二次买入
sell2=max(sell2', buy2'+prices[i]) // 前一天第二次卖出,今天不操作/今天第二次卖出
最后最大的利润在0,sell1,sell2之间产生 理清所有可能的状态,和状态之间怎么转换

func maxProfit(prices []int) int {
    //dp[n] 第n天卖出能获取的最大利润
    buy1, sell1 := -prices[0], 0
    buy2, sell2 := -prices[0], 0
    for i := 1; i < len(prices); i ++ {
       buy1Pre :=  buy1
       sell1Pre := sell1
       buy2Pre := buy2 

       buy1 =  max(buy1Pre, -prices[i])
       sell1 = max(sell1, buy1Pre + prices[i])
       buy2 = max(buy2Pre, sell1Pre - prices[i])
       sell2 = max(sell2, buy2Pre + prices[i])
    }
    return max(sell1, sell2)
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}