1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class BestTimeToBuyAndSellStockIII { public int maxProfit(int[] prices) { if (prices.length < 2) { return 0; } int[] before = new int[prices.length]; int[] after = new int[prices.length]; before[0] = 0; after[prices.length - 1] = 0; int min = prices[0]; for (int i = 1; i < prices.length; i++) { min = Math.min(min, prices[i]); before[i] = Math.max(before[i - 1], prices[i] - min); } int max = prices[prices.length - 1]; for (int i = prices.length - 2; i >= 0; i--) { max = Math.max(max, prices[i]); after[i] = Math.max(after[i + 1], max - prices[i]); } max = 0; for (int i = 0; i < prices.length; i++) { if (before[i] + after[i] > max) { max = before[i] + after[i]; } } return max; } }
|