先說明一下這是後知後覺的解答,所謂後知就是股票價格已知存在陣列(清單),當然就要用迴圈練習,雙迴圈暴力解需時O(n**2),當然不用,採python單一迴圈解答「最佳股票的買賣時機#LeetCode 121 Best Time to Buy and Sell Stock」,解法簡單快速O(n)時間。這是僅能一次買賣的問題,還有其他類似的問題陸續解出。
[code on Leetcode]https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solutions/3758901/c-python-greedy-explain-w-pyplot/
[這是可當日沖銷的無交易費,100%C++ 解答LeetCode 122 Best Time to Buy and Sell Stock 2]https://youtu.be/sJd7Q0HyyRg
- class Solution:
- def maxProfit(self, prices):
- """
- 計算股票的最大利潤。
- 參數:
- prices (List[int]): 一系列整數,代表不同日子的股票價格。
- 返回值:
- int: 可達到的最大利潤。
- """
- # 初始利潤為 0
- profit = 0
- # 設定購買價格為第一天的價格
- buy = prices[0]
- # 遍歷股價列表
- for x in prices[1:]:
- # 更新購買價格為目前價格和之前購買價格中的最小值
- buy = min(buy, x)
- # 更新利潤為目前利潤和當天賣出後的利潤的最大值
- profit = max(profit, x - buy)
- return profit
- def main():
- # 範例使用:
- prices = [7, 1, 5, 3, 6, 4] # 不同日子的股票價格範例
- solution = Solution()
- max_profit = solution.maxProfit(prices)
- print("最大利潤:", max_profit)
- if __name__ == "__main__":
- main()
matplotlib.pyplot繪圖部份如下
- import matplotlib.pyplot as plt
- prices = [7,1,5,3,6,4]
- plt.plot(prices, 'go--')
- plt.savefig('prices.png')
- plt.show()
沒有留言:
張貼留言