文中所有图片中循环箭头上的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就行了。