題目:
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