LeetCode 筆記 - 121. Best Time to Buy and Sell Stock

題目在此 121. Best Time to Buy and Sell Stock

給定每天股票的價格,請找出一買一賣之間,最大的獲利是多少

解題思維

基本邏輯很簡單

  1. 如果找到新低點,那清空之前的最高價,因為你不可能今天買了回到過去賣
  2. 如果找到新高點,那請根據目前的低點計算獲利,並記錄最高的獲利

完成 😆

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def maxProfit(self, prices: List[int]) -> int:

low_price = prices[0]
high_price = 0

result = 0
for p in prices:

if low_price > p:
low_price = p
high_price = p + result
elif high_price < p:
high_price = p

result = max(result, high_price - low_price)

return result