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).

思路:

将vector分成两部分,用Best Time to Buy and Sell Stock I的方法求得两部分的最大值,然后求和的最大值。要求两部分的最大值需要先正面扫描一遍求得0到i的最大值,在反方向扫描一遍求i到n-1的最大值。

代码:

 1     int maxProfit(vector<int> &prices) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         int n = prices.size();
 5         if(n == 0)
 6             return 0;
 7         vector<int> first(n, 0), second(n, 0);
 8         int min = prices[0], maxProfit = 0, max = prices[n-1];
 9         first[0] = 0;
10         for(int i = 1; i < n; i++){
11             if(prices[i] < min){
12                 min = prices[i];
13             }
14             if(prices[i] - min > maxProfit){
15                 maxProfit = prices[i] - min;
16             }
17             first[i] = maxProfit;
18         }
19         second[n-1] = 0;
20         maxProfit = 0;
21         for(int i = n-2; i >= 0; i--){
22             if(prices[i] > max){
23                 max = prices[i];
24             }
25             if(max - prices[i] > maxProfit){
26                 maxProfit = max - prices[i];
27             }
28             second[i] = maxProfit;
29         }
30         maxProfit = first[0] + second[0];
31         for(int i = 1; i < n; i++){
32             if(first[i] + second[i] > maxProfit)
33                 maxProfit = first[i] + second[i];
34         }
35         return maxProfit;
36     }

 

posted on 2013-11-09 23:47  waruzhi  阅读(166)  评论(0编辑  收藏  举报

导航