150強訪談中等

買賣股票的最佳時機(有冷卻時間)

針對「帶冷卻時間買賣股票的最佳時機」問題的詳細指南和 Python 實施。

問題陳述

中等

給定一個價格數組,其中價格[i] 是給定股票第 i 天的價格。

找出你能獲得的最大利潤。您可以根據需要完成任意多次交易(即多次買入一股股票並賣出一股股票),但有以下限制:

- 出售股票後,您無法在第二天(即冷卻日)購買股票。

注意:您不得同時進行多項交易(即,您必須先賣出股票,然後才能再次購買)。

寫一個函數 maxProfit(prices: List[int]) -> int

約束條件
  • 1 <= len(prices) <= 5000
  • 0 <= prices[i] <= 1000

範例

Example 1
Input
prices = [1,2,3,0,2]
Output
3
Explanation

Transactions = [buy, sell, cooldown, buy, sell].

Example 2
Input
prices = [1]
Output
0
Explanation

No transaction can be made.

Need a Hint?
考慮使用 2D DP 特定的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。