【leetcode】123. Best Time to Buy and Sell Stock III
题目如下:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.Example 2:
Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.Example 3:
Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
解题思路:题目要求最多只有两次交易。如果进行0次交易,output是0;如果只进行一次,只需要遍历一次Input,记录历史出现过的最小值,用当前元素减去最小值即为在当前日期卖出股票可以获得的最大利润,遍历完成数组求得最大值即可;如果进行两次交易,最关键的一点找出第一次交易卖出的日期;因为这个日期相当于把Input分成两段并且每段只进行一次交易,前后两段的最大利润的和即为总的最大利润,在前面提到的只进行一次交易的时候,很容易求得每一个交易日期可以获得的最大利润,记 dp_t1_max[i]为第i个日期进行一次出售时候的最大利润。接下来再从后往前遍历Input,同样可以求出每个日期反方向第一次(即为正向第二次)交易的最大利润,记dp_t2[j]为正向第二次交易的获得的最大利润,那么总的最大利润就是 dp_t1_max[j-1] - dp_t2[j] 。
代码如下:
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) <= 1: return 0 dp_t1 = [0] * len(prices) dp_t2 = [0] * len(prices) dp_t1_max = [0] * len(prices) t1_min = prices[0] res = 0 t1_max = 0 for i in range(1,len(prices)): dp_t1[i] = prices[i] - t1_min t1_min = min(t1_min,prices[i]) t1_max = max(t1_max,dp_t1[i]) dp_t1_max[i] = t1_max res = t1_max t2_max = prices[-1] for i in range(len(prices)-1,0,-1): dp_t2[i] = prices[i] - t2_max t2_max = max(t2_max,prices[i]) res = max(res,dp_t1_max[i-1] - dp_t2[i]) #print dp_t1 #print dp_t2 #print dp_t1_max return res