122. Best Time to Buy and Sell Stock II
这道题有两种解决办法,第一种是找到峰值和谷值并计算最大利润,第二种是用了累加的思想,对峰谷值方法进行了简化。
峰谷值法:遍历数组找先到第一个谷值,再找到第一个峰值,计算差值加到最大利润中,然后再从当前位置找下一个谷值和峰值,直到结束。
改进版:遍历数组,如果当前位置的价格比前一位高,就把差价加到总利润中,直到结束。
峰谷值法
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxprofit = 0
i = 0
while i < len(prices) - 1:
while i < len(prices) - 1 and prices[i] >= prices[i+1]:
i += 1
valley = prices[i]
while i < len(prices) - 1 and prices[i] <= prices[i+1]:
i += 1
peak = prices[i]
maxprofit += peak - valley
return maxprofit
改进
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxprofit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i-1]:
maxprofit += prices[i] - prices[i-1]
return maxprofit
LeetCode #122. Best Time to Buy and Sell Stock II
原文:https://www.cnblogs.com/RatsCommander/p/13857038.html