1. 程式人生 > 其它 >【Leetcode每日筆記】122.買賣股票的最佳時機IV(Python)

【Leetcode每日筆記】122.買賣股票的最佳時機IV(Python)

技術標籤:LeetCode一週一結leetcodepython資料結構動態規劃演算法

文章目錄

題目

給定一個整數陣列 prices ,它的第 i 個元素 prices[i] 是一支給定的股票在第 i 天的價格。

設計一個演算法來計算你所能獲取的最大利潤。你最多可以完成 k 筆交易。

注意:你不能同時參與多筆交易(你必須在再次購買前出售掉之前的股票)。

示例 1:

輸入:k = 2, prices = [2,4,1] 輸出:2 解釋:在第 1 天 (股票價格 = 2) 的時候買入,在第 2 天

(股票價格 = 4) 的時候賣出,這筆交易所能獲得利潤 = 4-2 = 2 。

示例 2:

輸入:k = 2, prices = [3,2,6,5,0,3] 輸出:7 解釋:在第 2 天 (股票價格 = 2) 的時候買入,在第 3
天 (股票價格 = 6) 的時候賣出, 這筆交易所能獲得利潤 = 6-2 = 4 。
隨後,在第 5 天 (股票價格 = 0) 的時候買入,在第 6 天 (股票價格 = 3) 的時候賣出, 這筆交易所能獲得利潤 = 3-0 = 3 。

提示:

0 <= k <= 109
0 <= prices.length <= 1000
0 <= prices[i] <= 1000

解題思路

動態規劃

狀態定義

buy[i][j]表示對於陣列price中的價格而言,進行恰好j筆交易,並且手上持有一隻股票,這種情況下的最大利潤;用sell[i][j]表示恰好進行j筆交易,並且當前手上不持有股票,這種情況下的最大利潤。可以簡單理解為,只有當賣出股票後,此次交易才算完成。

狀態轉移方程

buy[i][j]=max{buy[i−1][j],sell[i−1][j]−price[i]}
sell[i][j]=max{sell[i−1][j],buy[i−1][j−1]+price[i]}
具體過程可參考文末的連結

程式碼

class Solution:
    def maxProfit
(self, k: int, prices: List[int]) -> int: if not prices or prices == sorted(prices,reverse=True): return 0 k = min(k,len(prices)//2) buy = [[0] * (k+1) for _ in range(len(prices))] sell = [[0] * (k+1) for _ in range(len(prices))] buy[0][0],sell[0][0] = -prices[0],0 for i in range(1,k+1): buy[0][i] = sell[0][i] = float('-inf') for i in range(1,len(prices)): buy[i][0] = max(buy[i - 1][0], sell[i - 1][0] - prices[i]) for j in range(1,k+1): buy[i][j] = max(buy[i-1][j],sell[i-1][j]-prices[i]) sell[i][j] = max(sell[i-1][j],buy[i-1][j-1]+prices[i]) return max(sell[-1])

【Leetcode每日筆記】122.買賣股票的最佳時機II(Python)