題目出處
122. Best Time to Buy and Sell Stock II
難度
medium
個人範例程式碼
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
for i, price in enumerate(prices):
if i > 0:
one_day_profit = prices[i] - prices[i-1]
max_profit += one_day_profit if one_day_profit >= 0 else 0
return max_profit
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解
算法說明
可以一天內即時的進行買賣,我們最好的收益就是「從頭到尾都沒有損失的最佳情況」,
因此我們只要計算
- 當「今日 - 前日 受益 > 0」,我們就加上收益,
- 當「收益 <= 0」,我們就 +0
input handling
x
Boundary conditions
用 for 來控制搜尋範圍