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.
class Solution { public int maxProfit(int[] prices) { if(prices.length == 0) return 0; int n = prices.length; int[] f1 = new int[n]; int[] f2 = new int[n]; int valley = prices[0]; for(int i = 1; i < n; i++) { valley = Math.min(valley, prices[i]); f1[i] = Math.max(f1[i - 1], prices[i] - valley); } int peak = prices[n - 1]; for(int j = n - 2; j >= 0; j--) { peak = Math.max(peak, prices[j]); f2[j] = Math.max(f2[j + 1], peak - prices[j]); } int res = 0; for(int i = 0; i < n; i++) { res = Math.max(res, f1[i] + f2[i]); } return res; } }
valley:从左边到当前最小的点。然后要获取在当前i(prices【i】 - valley)或者之前(f【i-1】)卖掉的最大值。
peak:从当前到右边最大的点。然后获取在这个点之后(f【j+1】)或者这个点(peak - prices【j】)卖掉的最大值。
.. 开辟两个数组f1和f2,f1[i]表示在price[i]之前进行一次交易所获得的最大利润,f2[i]表示在price[i]之后进行一次交易所获得的最大利润。则f1[i]+f2[i]的最大值就是所要求的最大值.
.. 找一个点,这个点之前买卖的最高收益加上这点之后买卖的最高收益就是全局最优解,相应的,一个顺序记录最高收益,一个倒序记录最高收益,最后寻找对应的最大和,
一次交易 = 一次买卖
两次交易 = 两次买卖
既然最多两次买卖,那不妨设两个数组,
f1:在i或者之前卖掉的话,在i可以得到的最大值
f2:在i或者i之后获得,在i之后卖可以得到的最大值
[]: 3,3,5,0,0,3,1,4
f1:0,0,2,2,2,3,3,4
f2:3,3,3,3,3,3,3,0
r: 3,3,5,5,5,6,6,4