LeetCode解题报告:309. Best Time to Buy and Sell Stock with Cooldown

Problem

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]

解题思路

  这一题和714. Best Time to Buy and Sell Stock with Transaction Fee, (714题解法)很像,如果上一题理解了,那么这一题就不是很难了。

  类似的,我们需要定义两个数组, h o l d hold hold s o l d sold sold,分别表示当天结束之后手里持有股票和手里没有股票的情况。分类讨论如下。

  假设今天结束之后,我们的手中持有股票,那么这个股票的来源有两个可能性,一个是昨天的股票没有卖出,状态一直顺延到了今天,所以手中才持有股票,还有一个可能性是我今天买入了一只股票,在这种可能性下,我们可以知道,由于存在一个窗口期,即隔一天才能买入股票,那么今天如果买入了股票,前天必然是卖出的状态才可以。在这两种情况下取较大的值,就是今天过后手中持有股票的最大收益。

  假设今天结束之后,手中没有持有股票,那么这种情况就和714题一致了,依然有两种情况,第一种是昨天手中就没有股票,今天也没有买,那么昨天的状态就顺延到了今天。第二种是昨天手中有股票,今天把它卖了,从中获取收益。我们取这两种情况中的较大者,就是今天结束之后手中没有持有股票的最佳收益。

   状态转移方程如下:

h o l d [ i ] = m a x ( s o l d [ i − 2 ] − p r i c e s [ i − 1 ] , h o l d [ i − 1 ] ) s o l d [ i ] = m a x ( h o l d [ i − 1 ] + p r i c e s [ i − 1 ] , s o l d [ i − 1 ] ) hold[i] = max(sold[i - 2] - prices[i - 1], hold[i - 1]) \\ sold[i] = max(hold[i - 1] + prices[i - 1], sold[i - 1]) hold[i]=max(sold[i2]prices[i1],hold[i1])sold[i]=max(hold[i1]+prices[i1],sold[i1])

  代码如下:(注意:第一天只能买入,无法卖出。)

class Solution:
    def maxProfit(self, prices: list) -> int:
        if not prices:
            return 0
        hold = [0] * (len(prices) + 1)
        sold = [0] * (len(prices) + 1)

        hold[1] = - prices[0]

        for i in range(2, len(hold)):
            hold[i] = max(sold[i - 2] - prices[i - 1], hold[i - 1])
            sold[i] = max(hold[i - 1] + prices[i - 1], sold[i - 1])

        return sold[-1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值