题目 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
关键是我们需要考虑到紧跟谷的每一个峰值以最大化利润。如果我们试图跳过其中一个峰值来获取更多利润,那么我们最终将失去其中一笔交易中获得的利润,从而导致总利润的降低。连续的峰加起来的收益肯定比最后卖的收益高,画图!
def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 i = 0 valley = prices[0] peak = prices[0] maxprofit = 0 while i < len(prices) - 1: # 大小号别反了,要一直循环到i<i+1为止,所以判断的时候应该是i>=i+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参考微分积分思想进行改进,因为可以连续买入,所以每个升的小段都该是我们要买的。
def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 maxprofit = 0 for i in range(1,len(prices)): if(prices[i] > prices[i-1]): maxprofit += prices[i] - prices[i-1] return maxprofit