题目简述
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
解题思路:
1.波谷波峰法:考虑波谷和紧跟的波峰,两者作差,重复此过程。
由图可知:A+B>C,所以要找临近的波峰波谷,而不是放弃相邻的,去找相差更大的波峰波谷
2.优化法:所有赚取交易日都卖出(一直赚钱),所有亏算交易日都不出售(一直不亏钱)
if len(prices)=0:
return 0
maxprofit=0
for i in range(len(prices)-1):
if prices[i]<prices[i+1]:
maxprofit+=prices[i+1]-prices[i]
return maxprofit
if len(prices)=0:
return 0
i=0
profit=0
while (i< len(prices)-1):
while (i < len(prices)-1 & prices[i]>=prices[i+1]):
i+=1
vally=prices[i]
while (i < len(prices)-1 & prices[i]<=prices[i+1]):
i+=1
peak = prices[i]
profit+=peak-vally
return profit