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).
分析:
看到最大利润,首先想到动态规划;
动态规划,我们就要找子问题。
就此问题而言,两手交易,并且两手交易不能交叉,实际上是把数组分成两段,分别求前后两段的最大利润,
假设分割点是k,就是求[ 0, k ] 和 [ k, len-1] 的最大利润,注意,这里k是可以交叉的,因为题意是之多两手交易,如果刚好在k点卖出又买入,就可以认为总共进行了一手买卖。
这样,我们要分别计算每点的最大利润。
[0, k] 最大利润用一个动态规划,
[k, len-1] 最大利润用一个动态规划。
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length==0) return 0;
int max=0;
int[] left = new int[prices.length];
int[] right = new int[prices.length];
process(prices, left, right);
for(int i=0; i<prices.length; i++)
max = Math.max(max, left[i]+right[i]);
return max;
}
private void process(int[] prices, int[] left, int[] right){
left[0]=0;
int min=prices[0];
for(int i=1; i<left.length; i++){
left[i] = Math.max(left[i-1], prices[i]-min);
min = Math.min(min, prices[i]);
}
right[right.length-1]=0;
int max=prices[right.length-1];
for(int i=right.length-2; i>=0; i--){
right[i] = Math.max(right[i+1], max-prices[i]);
max = Math.max(max, prices[i]);
}
}
}