|
| 1 | +/* |
| 2 | +Say you have an array for which the ith element is the price of a given stock on day i. |
| 3 | +
|
| 4 | +Design an algorithm to find the maximum profit. You may complete at most two transactions. |
| 5 | +
|
| 6 | +Note: |
| 7 | +You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). |
| 8 | + */ |
| 9 | +//idea comes from peking2 of Mitbbs |
| 10 | +// use two array dp1 and dp2 to traversal from both end |
| 11 | + |
| 12 | +public class BestTimeToBuyAndSellStockIII { |
| 13 | + public int maxProfit(int[] prices) { |
| 14 | + // Start typing your Java solution below |
| 15 | + // DO NOT write main() function |
| 16 | + if (prices.length == 0 || prices.length == 1) { |
| 17 | + return 0; |
| 18 | + } |
| 19 | + int len = prices.length; |
| 20 | + int[] dp1 = new int[prices.length]; |
| 21 | + int[] dp2 = new int[prices.length]; |
| 22 | + int min = prices[0]; |
| 23 | + int max = prices[len - 1]; |
| 24 | + |
| 25 | + // for dp1: travel from left to right |
| 26 | + System.out.print(" " + dp1[0]); |
| 27 | + |
| 28 | + for (int i = 1; i < len; i++) { |
| 29 | + min = Math.min(min, prices[i]); |
| 30 | + dp1[i] = Math.max(dp1[i - 1], prices[i] - min); |
| 31 | + System.out.print(" " + dp1[i]); |
| 32 | + } |
| 33 | + System.out.println(); |
| 34 | + // for dp2: travel from right to left |
| 35 | + System.out.print(" " + dp2[len - 1]); |
| 36 | + for (int j = len - 2; j >= 0; j--) { |
| 37 | + max = Math.max(max, prices[j]); |
| 38 | + dp2[j] = Math.max(dp2[j + 1], max - prices[j]); |
| 39 | + System.out.print(" " + dp2[j]); |
| 40 | + } |
| 41 | + System.out.println(); |
| 42 | + int ans = 0; |
| 43 | + for (int k = 0; k < len; k++) { |
| 44 | + ans = Math.max(ans, dp1[k] + dp2[k]);// You may not engage in |
| 45 | + // multiple transactions at |
| 46 | + // the same time |
| 47 | + } |
| 48 | + return ans; |
| 49 | + |
| 50 | + } |
| 51 | + |
| 52 | + public static void main(String[] args) { |
| 53 | + BestTimeToBuyAndSellStockIII o = new BestTimeToBuyAndSellStockIII(); |
| 54 | + int[] prices = { 2, 1, 2, 1, 0, 1, 2 }; |
| 55 | + System.out.println(o.maxProfit(prices)); |
| 56 | + } |
| 57 | +} |
0 commit comments