leetcode122 Best Time to Buy and Sell Stock II
1 """ 2 Say you have an array for which the ith element is the price of a given stock on day i. 3 Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). 4 Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 5 Example 1: 6 Input: [7,1,5,3,6,4] 7 Output: 7 8 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. 9 Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. 10 Example 2: 11 Input: [1,2,3,4,5] 12 Output: 4 13 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. 14 Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are 15 engaging multiple transactions at the same time. You must sell before buying again. 16 Example 3: 17 Input: [7,6,4,3,1] 18 Output: 0 19 Explanation: In this case, no transaction is done, i.e. max profit = 0. 20 """ 21 """ 22 搞笑的一题,容易想复杂 23 可以与leetcode121联系来看https://www.cnblogs.com/yawenw/p/12261726.html 24 其实这个题要求一天不能同时买和卖股票, 25 而且必须再一笔交易完成之后才能进行下一笔交易 26 假设序列是a <= b <= c <= d [1, 2, 3, 4] 27 最大利润 d - a = (b - a) + (c - b) + (d - c) 28 假设序列是a <= b, b >= c, c <= d [1, 5, 4, 8] 29 最大利润(b - a) + (d - b) 30 """ 31 class Solution: 32 def maxProfit(self, prices): 33 res = 0 34 for i in range(len(prices)-1): 35 if prices[i] < prices[i+1]: 36 res += prices[i+1]-prices[i] 37 return res