Python程式:求解股票市場單次交易最大利潤


假設我們有一份價格列表,按時間順序表示某公司股票的價格,我們需要找到僅進行一次買賣所能獲得的最大利潤。請記住,必須先買入才能賣出。

因此,如果輸入類似於 prices = [10, 12, 9, 6, 8, 12],則輸出為 6,因為我們可以在價格為 6 時買入,在價格為 12 時賣出。

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

  • max_profit := 0
  • min_stock := 無窮大
  • 對於 prices 中的每個價格,執行以下操作:
    • max_profit := max_profit 和 (price - min_stock) 之間的最大值
    • min_stock := min_stock 和 price 之間的最小值
  • 返回 max_profit

讓我們來看下面的實現,以便更好地理解:

示例

線上演示

class Solution:
   def solve(self, prices):
      max_profit = 0
      min_stock = float('inf')
      for price in prices:
         max_profit = max(max_profit, price - min_stock)
         min_stock = min(min_stock, price)
      return max_profit
ob = Solution()
print(ob.solve([10, 12, 9, 6, 8, 12]))

輸入

[10, 12, 9, 6, 8, 12]

輸出

6

更新於:2020年10月5日

1K+ 瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.