###### tags: `LeetCode`,`Python3`,`Medium` # Medium-122. Best Time to Buy and Sell Stock II ### **題目連結:** [**Best Time to Buy and Sell Stock II**](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/) ### **解題方向** * 遍歷價格陣列:從第二天開始遍歷,因為我們需要與前一天的價格進行比較。 * 獲取利潤:每當發現當天的價格比前一天高時,我們就認為可以通過這次買入和賣出來賺取利潤,將這次的利潤累積到總利潤中。 * 返回結果:遍歷結束後,max_profit 就是我們能夠賺取的最大總利潤。 ### **完整程式碼** ```Python= class Solution: def maxProfit(self, prices: List[int]) -> int: # 初始化最大利潤為0 max_profit = 0 # 遍歷價格陣列的每一天 for i in range(1, len(prices)): # 如果今天的價格比前一天高,意味著有利潤可以賺取 if prices[i] > prices[i - 1]: # 將今天的價格與昨天的價格差額加入總利潤中 max_profit += prices[i] - prices[i - 1] # 返回總的最大利潤 return max_profit ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up