Question
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.
Code
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int ret = 0;
int len = prices.length;
int[] leftProfile = new int[len];
int min = prices[0];
leftProfile[0] = 0;
for (int i = 1; i < len; i++) {
min = Math.min(min, prices[i]);
leftProfile[i] = Math.max(leftProfile[i - 1], prices[i] - min);
}
int max = Integer.MIN_VALUE;
int profile = 0;
for (int i = len - 1; i >= 0; i--) {
max = Math.max(max, prices[i]);
profile = Math.max(profile, max - prices[i]);
ret = Math.max(ret, profile + leftProfile[i]);
}
return ret;
}