Leetcode 122. Best Time to Buy and Sell Stock II
只要能卖就马上卖,最后就是最优解.
因为如果捂着不卖,后面再卖,不会更优的.比如:[1, 7, 2, 3, 6, 7, 6, 7]这组数据,根据下图(图来自leetcode官方题解)A+B+C=D.遇到能卖的就卖就好.
class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 ans=0 for i in range(1,len(prices)): if prices[i]>prices[i-1]: ans+=prices[i]-prices[i-1] return ans