121. Best Time to Buy and Sell Stock

題目
思路

  1. 最直覺的想法是從頭開始 traverse array,針對每一個 price 都去算一次那個位置之後的所有可能利潤,不過這樣會是兩個巢狀 for-loop,時間複雜度是 O(n^2),太大了
  2. 有沒有辦法只 traverse 一次 array 就好?
  3. 利潤是由買價和賣價得出,知道最低買價和最高賣價就可以得出答案。有辦法設定這兩個變數,然後隨著 array traversal 不斷更新嗎?
    • 可以把 最高賣價 改成 最大利潤,因為這個才是需回傳的答案
Python 3 solution
1
2
3
4
5
6
7
8
9
def maxProfit(self, prices: List[int]) -> int:
min_bid = float('inf')
max_profit = 0
for price in prices:
if price < min_bid:
min_bid = price
elif price - min_bid > max_profit:
max_profit = price - min_bid
return max_profit
#

評論

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×