首页 > 代码库 > LeetCode123 Best Time to Buy and Sell Stock III

LeetCode123 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. (Hard)

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

 

分析:

最多购买两次股票且不能同时拥有,所以买卖两次肯定分布在前后两个不同的区间。

设dp(i) = 区间[0,1,2...i]的最大利润 + 区间[i,i+1,....n-1]的最大利润,那么本题的最大利润 = max{dp[0],dp[1],dp[2],...,dp[n-1]}.

而对于式子中两个区间内分别只能有一次买卖,这是Best Time to Buy and Sell Stock I的问题。

代码:

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         int len = prices.size();
 5         if(len <= 1) {
 6             return 0;
 7         }
 8         int maxFromHead[len];
 9         maxFromHead[0] = 0;
10         int minprice = prices[0], maxprofit = 0;
11         for(int i = 1; i < len; i++) {
12             minprice = min(prices[i-1], minprice);
13             if(maxprofit < prices[i] - minprice)
14                 maxprofit = prices[i] - minprice;
15             maxFromHead[i] = maxprofit;
16         }
17         int maxprice = prices[len - 1];
18         int res = maxFromHead[len-1];
19         maxprofit = 0;
20         for(int i = len-2; i >=0; i--) {
21             maxprice = max(maxprice, prices[i+1]);
22             if(maxprofit < maxprice - prices[i])
23                 maxprofit = maxprice - prices[i];
24             if(res < maxFromHead[i] + maxprofit)
25                 res = maxFromHead[i] + maxprofit;
26         }
27         return res;
28     }
29 };

 

LeetCode123 Best Time to Buy and Sell Stock III