【Leetcode每日筆記】309. 最佳買賣股票時機含冷凍期(Python)
阿新 • • 發佈:2020-12-29
技術標籤:LeetCode一週一結leetcode動態規劃演算法資料結構python
文章目錄
題目
給定一個整數陣列,其中第 i 個元素代表了第 i 天的股票價格 。
設計一個演算法計算出最大利潤。在滿足以下約束條件下,你可以儘可能地完成更多的交易(多次買賣一支股票):
你不能同時參與多筆交易(你必須在再次購買前出售掉之前的股票)。 賣出股票後,你無法在第二天買入股票 (即冷凍期為 1 天)。
示例:
輸入: [1,2,3,0,2] 輸出: 3 解釋: 對應的交易狀態為: [買入, 賣出, 冷凍期, 買入, 賣出]
解題思路
動態規劃
狀態定義
buy[i]表示第i天持股的最大利潤,sell[i]表示第i天不持股的最大利潤
狀態轉移方程
需要跳過冷凍期,那麼第i天持股,需要考慮的是前兩天不持股的情況;
前兩天的定義:
buy[0] ,buy[1]= -prices[0],max(-prices[1],-prices[0])
sell[0],sell[1] = 0,max(prices[1]-prices[0],0)
後面的方程
buy[i] = max(buy[i-1],sell[i-2]-prices[i])
sell[i] = max(sell[i-1],buy[i-1]+prices[i])
程式碼
class Solution :
def maxProfit(self, prices: List[int]) -> int:
if not prices or prices == sorted(prices,reverse=True):
return 0
buy = [0 for _ in range(len(prices))]
sell = [0 for _ in range(len(prices))]
buy[0] ,buy[1]= -prices[0],max(-prices[1],-prices[0])
sell[ 0],sell[1] = 0,max(prices[1]-prices[0],0)
for i in range(2,len(prices)):
buy[i] = max(buy[i-1],sell[i-2]-prices[i])
sell[i] = max(sell[i-1],buy[i-1]+prices[i])
return max(sell)