herrDeng網內搜尋

自訂搜尋

Ads

2024年3月27日 星期三

python單一迴圈解答最佳股票的買賣時機LeetCode 121 Best Time to Buy and Sell Stock



先說明一下這是後知後覺的解答,所謂後知就是股票價格已知存在陣列(清單),當然就要用迴圈練習,雙迴圈暴力解需時O(n**2),當然不用,採python單一迴圈解答「最佳股票的買賣時機#LeetCode 121  Best Time to Buy and Sell Stock」,解法簡單快速O(n)時間。這是僅能一次買賣的問題,還有其他類似的問題陸續解出。
[這是可當日沖銷的無交易費,100%C++ 解答LeetCode 122 Best Time to Buy and Sell Stock 2]https://youtu.be/sJd7Q0HyyRg
  1. class Solution:
  2. def maxProfit(self, prices):
  3. """
  4. 計算股票的最大利潤。
  5.  
  6. 參數:
  7. prices (List[int]): 一系列整數,代表不同日子的股票價格。
  8.  
  9. 返回值:
  10. int: 可達到的最大利潤。
  11. """
  12. # 初始利潤為 0
  13. profit = 0
  14. # 設定購買價格為第一天的價格
  15. buy = prices[0]
  16. # 遍歷股價列表
  17. for x in prices[1:]:
  18. # 更新購買價格為目前價格和之前購買價格中的最小值
  19. buy = min(buy, x)
  20. # 更新利潤為目前利潤和當天賣出後的利潤的最大值
  21. profit = max(profit, x - buy)
  22. return profit
  23.  
  24. def main():
  25. # 範例使用:
  26. prices = [7, 1, 5, 3, 6, 4] # 不同日子的股票價格範例
  27. solution = Solution()
  28. max_profit = solution.maxProfit(prices)
  29. print("最大利潤:", max_profit)
  30.  
  31. if __name__ == "__main__":
  32. main()

matplotlib.pyplot繪圖部份如下

  1. import matplotlib.pyplot as plt
  2. prices = [7,1,5,3,6,4]
  3. plt.plot(prices, 'go--')
  4. plt.savefig('prices.png')
  5. plt.show()

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章