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 (ie, you must sell the stock before you buy again).
public class Solution { public int maxProfit(int[] prices) { // The transaction process is buy->sell-buy->sell or buy-->sell int n = prices.length; if (n <= 1) return 0; int[] maxProfitUntil = new int[n]; int[] maxProfitFrom = new int[n]; // Unitl operation maxProfitUntil[0] = 0; int minCur = prices[0]; for (int i = 1; i < n; i++) { maxProfitUntil[i] = Math.max(maxProfitUntil[i-1], prices[i]-minCur); minCur = Math.min(minCur, prices[i]); } // From operation maxProfitFrom[0] = maxProfitUntil[n-1]; maxProfitFrom[n-1] = 0; int maxCur = prices[n-1]; for (int i = n-2; i > 0; i--) { maxProfitFrom[i] = Math.max(maxProfitFrom[i+1], maxCur - prices[i]); maxCur = Math.max(maxCur, prices[i]); } int maxProfit = maxProfitFrom[0]; for (int i = 1; i < n-1; i++) maxProfit = Math.max(maxProfit, maxProfitUntil[i]+maxProfitFrom[i+1]); return maxProfit; } }
No comments:
Post a Comment