leetcode: Best Time to Buy and Sell Stock with Cooldown

文中所有图片中循环箭头上的wait都应该改为loop,意为经历一次循环。

Question:

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:

prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]

Solution:

The series of problems are typical dp. The key for dp is to find the variables to represent the states and deduce the transition function.

本题的状态转移图如下:
这里写图片描述
据此写出状态转移方程:

sell[i] = buy[i-1] + prices[i]
buy[i] = max(rest[i-1]-prices[i],buy[i-1])
rest[i] = max(rest[i-1],sell[i-1])

由于涉及到的变量有限,可以将空间复杂度从O(n)降到O(1):

prev_sell = sell
sell = buy + prices[i]
buy = max(rest-prices[i],buy)
rest = max(prev_sell,rest)

完整代码:

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) < 2:
            return 0
        sell, buy, prev_sell,rest= 0, -prices[0], 0, 0
        for price in prices:
            prev_sell = sell
            sell = buy + price
            buy = max(rest-price,buy)
            rest = max(prev_sell,rest)
        return max(rest,sell)

Advanced Solution

从状态转移图可以看出,从sell状态到rest状态并没有价格的改变,只是必须强制休息一回合。所以一定有rest[i]<=sell[i-1],状态转移图如下:
这里写图片描述
转移方程:

buy[i] = max(sell[i-2]-prices[i],buy[i-1])
sell[i] = max(buy[i-1]+prices[i],sell[i-1])

cooldown的限制就隐藏在sell[i-2]中。
同样地可以变为空间复杂度为O(1)的形式:

prev_buy = buy
buy = max(prev_sell-prices[i],prev_buy)
prev_sell = sell
sell = max(prev_buy+prices[i],prev_sell)

可以看到每一次buy在更新前,上一次循环中都有两次sell状态的更新,prev_sell在上一循环对应sell[i-1],本轮循环就对应sell[i-2]。
循环完成之后只要返回sell就行了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值