劍指offer面試題63. 股票的最大利潤(動態規劃)

題目描述

假設把某股票的價格按照時間先後順序存儲在數組中,請問買賣該股票一次可能獲得的最大利潤是多少?
在這裏插入圖片描述

思路

詳見鏈接

代碼

class Solution:
	def maxProfit(self, prices:List[int])->int:
		cost, profit = float("inf"), 0
		for price in prices:
			cost = min(cost, price)
			profit = max(profit, price - cost)
		return profit

複雜度

時間複雜度 O(N): 其中 NN 爲 prices列表長度,動態規劃需遍歷 prices 。
空間複雜度 O(1) : 變量 cost 和 profit 使用常數大小的額外空間。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章