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).
Solution 1:
public int maxProfit(int[] prices) {
int n = prices.length;
if(n<=1) return 0;
// dp数组保存左边和右边的利润最大值
int[] leftProfit = new int[n]; // [0,i]区间的最大利润
int[] rightProfit = new int[n]; // [i,n-1]区间的最大利润
//正向遍历,leftProfit[i]表示 prices[0...i]内做一次交易的最大收益.
int minPrice = prices[0]; //最低买入价
for(int i=1; i<n; i++) {
minPrice = Math.min(minPrice, prices[i]); // 更新最小买入价
// i的最大利润为(i-1的利润)和(当前卖出价和之前买入价之差)的较大者
leftProfit[i] = Math.max(leftProfit[i-1], prices[i]-minPrice);
}
//逆向遍历, rightProfit[i]表示 prices[i...n-1]内做一次交易的最大收益.
int maxPrice = prices[n-1]; //最高卖出价
for(int i=n-2; i>=0; i--) {
maxPrice = Math.max(maxPrice, prices[i]); // 更新最高卖出价
// i的最大利润为(i+1的利润)和(最高卖出价和当前买入价之差)的较大者
rightProfit[i] = Math.max(rightProfit[i+1], maxPrice-prices[i]);
}
int maxProfit = 0;
for(int i=0; i<n; i++) {
maxProfit = Math.max(maxProfit, leftProfit[i]+rightProfit[i]);
}
return maxProfit;
}
Solution 2:
忘记上面的方法吧,下面这个解法更好。
public int maxProfit(int[] prices) {
int len = prices.length;
if (len == 0) return 0;
int k = 3; // 2 transactions
int[][] f = new int[k][len];
for (int i = 1; i < k; i++) {
int tmpMax = f[i-1][0] - prices[0];
for (int j = 1; j < len; j++) {
f[i][j] = Math.max(f[i][j-1], tmpMax + prices[j]);
tmpMax = Math.max(tmpMax, f[i-1][j] - prices[j]);
}
}
return f[k-1][len-1];
}