Best Time to Buy and Sell Stock III
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 (ie, you must sell the stock before you buy again).
public class Solution {
public int maxProfit(int[] prices) {
//four cases: c1:buy one, c2:sell one, c3:buy two, c4:sell two
//assume: 1.never sell one before buy one
// 2.never buy one before buy two
// 3.never buy two before sell two
// 4.never sell one before sell two
int b1= Integer.MIN_VALUE,s1=0,b2=Integer.MIN_VALUE,s2=0;
for(int i = 0; i < prices.length; i++){
int p = prices[i];
s2 = Math.max(s2,b2+p);
b2 = Math.max(b2,s1-p);
s1 = Math.max(s1,b1+p);
b1 = Math.max(b1,-p);
}
return s2;
}
}