题目:
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).
题解:
根据题目要求,最多进行两次买卖股票,而且手中不能有2只股票,就是不能连续两次买入操作。
所以,两次交易必须是分布在2各区间内,也就是动作为:买入卖出,买入卖出。
进而,我们可以划分为2个区间[0,i]和[i,len-1],i可以取0~len-1。
那么两次买卖的最大利润为:在两个区间的最大利益和的最大利润。
一次划分的最大利益为:Profit[i] = MaxProfit(区间[0,i]) + MaxProfit(区间[i,len-1]);
最终的最大利润为:MaxProfit(Profit[0], Profit[1], Profit[2], ... , Profit[len-1])。
代码如下:
1 public int maxProfit(int[] prices) {
2 if(prices == null || prices.length <= 1){
3 return 0;
4 }
5 int len = prices.length;
6 int maxProfit = 0;
7 int min = prices[0];
8 int arrayA[] = new int[len];
9
10 for(int i=1;i<prices.length;i++){
11 min=Math.min(min,prices[i]);
12 arrayA[i]=Math.max(arrayA[i-1],prices[i]-min);
13 }
14
15 int max = prices[len-1];
16 int arrayB[] = new int[len];
17 for(int i = len-2; i >= 0; i--){
18 max = Math.max(prices[i],max);
19 arrayB[i] = Math.max(max-prices[i],arrayB[i+1]);
20 }
21
22 for(int i = 0; i < len; i++){
23 maxProfit = Math.max(maxProfit,arrayA[i] + arrayB[i]);
24 }
25
26 return maxProfit;
27 }
2 if(prices == null || prices.length <= 1){
3 return 0;
4 }
5 int len = prices.length;
6 int maxProfit = 0;
7 int min = prices[0];
8 int arrayA[] = new int[len];
9
10 for(int i=1;i<prices.length;i++){
11 min=Math.min(min,prices[i]);
12 arrayA[i]=Math.max(arrayA[i-1],prices[i]-min);
13 }
14
15 int max = prices[len-1];
16 int arrayB[] = new int[len];
17 for(int i = len-2; i >= 0; i--){
18 max = Math.max(prices[i],max);
19 arrayB[i] = Math.max(max-prices[i],arrayB[i+1]);
20 }
21
22 for(int i = 0; i < len; i++){
23 maxProfit = Math.max(maxProfit,arrayA[i] + arrayB[i]);
24 }
25
26 return maxProfit;
27 }
Reference:
http://blog.csdn.net/u013027996/article/details/19414967