1.第一题:
这一道题的暴力解法反正一开始我是没有思路的,最后也是看了一下官方题解用顺序找到相邻的最高和最低,求其差值相加,代码如下:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
i=0
valley=prices[0]
peak=prices[0]
maxprofit=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