#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]
#主要思路:动态规划,从最后一步开始倒推:
#情况无非四种:
#1,Sell:持有一个股并卖出——上一步必然是2 or 3
#2,Hold:持有一个股并继续持有——上一步必然时2 or 3
#3,Buy:没有股票,买入——上一步必然是4
#4,CD:没有股票,不操作——上一步必然是1 or 4
#以i代表i时刻,Sell[i]意为"在i时刻执行Sell操作时的最大利润"
#写出四种行为的表达式:
#Sell[i] = max(Buy[i-1]+price, hold[i-1]+price)
#Hold[i] = max(Buy[i-1], hold[i-1])
#Buy[i] = CD[i-1]-price
#CD[i] = max(Sell[i-1], CD[i-1])
#“Now you want to maximize your total profit,
#but you don't know what action to take on day i such that you get the total maximum profit,
#so you try all 4 actions on every day.
#Suppose you take action 1 on day i, since there are two possible actions on day i-1, namely actions 2 and 3,
#you would definitely choose the one that makes your profit on day i more. Same thing for actions 2 and 4.
#So we now have an iterative algorithm.”——ElementNotFoundException
#另外初始的值设定很重要: At Stage 0 : sell, hold, buy, cd = 0, -prices[0], -prices[0], 0
#动态分布,从结果开始以最佳策略进行倒推论
class Solution(object):
def maxProfit(self, prices):
if not prices:
return 0
sell, hold, buy, cd = 0, -prices[0], -prices[0], 0
for price in prices:
sell, hold, buy ,cd = max(buy+price, hold+price), max(buy, hold), cd - price, max(sell,cd)
return max(sell,hold,buy,cd)