class Solution:
def maxProfit(self, prices: List[int]) -> int:
i, peak, valley, max_profit = 1, 0, 0, 0 #i从1开始
while i < len(prices):
while i < len(prices) and prices[i] <= prices[i-1]:
i += 1
valley = prices[i-1] #先找谷值
while i < len(prices) and prices[i] >= prices[i-1]:
i += 1
peak = prices[i-1] #再找峰值
max_profit += peak - valley #累加差值
return max_profit
或者与后一位比较:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
i, peak, valley, max_profit = 0, 0, 0, 0 #i从0开始
while i < len(prices)-1:
while i < len(prices)-1 and prices[i+1] <= prices[i]:
i += 1
valley = prices[i]
while i < len(prices)-1 and prices[i+1] >= prices[i]:
i += 1
peak = prices[i]
max_profit += peak - valley
return max_profit