Python程式:在最多買賣兩次股票的情況下找到最大利潤


假設我們有一個名為prices的數字列表,它按時間順序表示公司的股票價格,我們必須找到在最多買賣兩次股票的情況下可以獲得的最大利潤。我們必須先買入然後賣出。

因此,如果輸入類似於 prices = [2, 6, 3, 4, 2, 9],則輸出將為 11,因為我們可以在價格 2 買入,然後在 6 賣出,再次在 2 買入,並在 9 賣出。

為了解決這個問題,我們將遵循以下步驟 -

  • first_buy := -inf,first_sell := -inf
  • second_buy := -inf,second_sell := -inf
  • 對於 prices 中的每個 px,執行以下操作
    • first_buy := first_buy 和 -px 的最大值
    • first_sell := first_sell 和 (first_buy + px) 的最大值
    • second_buy := second_buy 和 (first_sell - px) 的最大值
    • second_sell := second_sell 和 (second_buy + px) 的最大值
  • 返回 0、first_sell 和 second_sell 的最大值

讓我們看看以下實現以更好地理解 -

示例

線上演示

class Solution:
   def solve(self, prices):
      first_buy = first_sell = float("-inf")
      second_buy = second_sell = float("-inf")
      for px in prices:
         first_buy = max(first_buy, -px)
         first_sell = max(first_sell, first_buy + px)
         second_buy = max(second_buy, first_sell - px)
         second_sell = max(second_sell, second_buy + px)
      return max(0, first_sell, second_sell)

ob = Solution()
prices = [2, 6, 3, 4, 2, 9]
print(ob.solve(prices))

輸入

[2, 6, 3, 4, 2, 9]

輸出

11

更新於: 2020年12月2日

223 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告