LeetCode 309. Best Time to Buy and Sell Stock with Cooldown (在具有冻结时间条件下买入和卖出股票的最佳时间)

原题

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]

Reference Answer

思路分析

这个题和714. Best Time to Buy and Sell Stock with Transaction Fee比较像。做题方法都是使用了两个数组:

cash 该天结束手里没有股票的情况下,已经获得的最大收益;
hold 该天结束手里有股票的情况下,已经获得的最大收益;
状态转移方程式这样的:

sell[i] = max(sell[i - 1], hold[i - 1] + prices[i])
hold[i] = max(hold[i - 1], (sell[i - 2] if i >= 2 else 0) - prices[i])

cash[i]代表的是手里没有股票的收益,这种可能性是今天卖了或者啥也没干。max(昨天手里有股票的收益+今天卖股票的收益,昨天手里没有股票的收益), 即max(sell[i - 1], hold[i - 1] + prices[i])

hold[i] 代表的是手里有股票的收益,这种可能性是今天买了股票或者啥也没干,今天买股票必须昨天休息。所以为max(今天买股票是前天卖掉股票的收益-今天股票的价格,昨天手里有股票的收益)。即 max(hold[i - 1], sell[i - 2] - prices[i])

该算法的时间复杂度是O(n),空间复杂度是O(n)。

Code

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices: return 0
        sell = [0] * len(prices)
        hold = [0] * len(prices)
        hold[0] = -prices[0]
        for i in range(1, len(prices)):
            sell[i] = max(sell[i - 1], hold[i - 1] + prices[i])
            hold[i] = max(hold[i - 1], (sell[i - 2] if i >= 2 else 0) - prices[i])
        return sell[-1]
  

进阶版
如果使用O(1)的空间复杂度,那么就可以写成下面这样:

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices: return 0
        prev_sell = 0
        curr_sell = 0
        hold = -prices[0]
        for i in range(1, len(prices)):
            temp = curr_sell
            curr_sell = max(curr_sell, hold + prices[i])
            hold = max(hold, (prev_sell if i >= 2 else 0) - prices[i])
            prev_sell = temp
        return curr_sell

Note

  • 这道题明知道就是用DP解决的,就是硬生生没想出解决思路。其主要愿意是自己陷入了只使用一条路径 dp = [0] * len(nums) 来解决问题,而这种方式在复杂条件下(如本题的卖在买之后,买之后需有一天间隔期),往往需要同时维护多条 dp 路径;
  • 参考答案这种 (sell[i - 2] if i >= 2 else 0) - prices[i]) 表达方式很巧妙,其单行条件判断表达式也值得学习 if not prices: return 0

参考文献

[1] https://blog.csdn.net/fuxuemingzhu/article/details/82656899

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值