题目链接: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).

这道题的要求是用数组中的数字表示股票的价格,然后最多允许2次买入卖出,计算最大利益。

Best Time to Buy and Sell StockBest Time to Buy and Sell Stock II类似的题目,这次是版本三了。

Best Time to Buy and Sell Stock同样的动态规划思路,然而这个问题可以延伸到最多可以k次买入卖出,因此分别用res[j]和cur[j]表示最高j次交易的全局最大利益和最高j次交易的当天卖出的最大利益。递推公式为:

  • cur[j] = max(res[j-1] + (diff>0 ? diff : 0), cur[j]+diff);
  • res[j] = max(res[j], cur[j])。

其中diff为当前股票价格和前一天的差值,即prices[i] - prices[i-1]。res[j-1] + (diff>0 ? diff : 0)表示全局进行j-1次交易,然后加上当天的交易(如果是赚钱的话),cur[j]+diff表示前一天的j次交易,然后加上今天的差值(这里因为cur[j]包含前一天卖出的交易,所以现在变成当天卖出,并不会增加交易次数,而且这里无论diff是不是大于0都一定要加上,因为否则就不满足cur[j]必须在当天卖出的条件了)。

时间复杂度:O(nk)(此题k=2)

空间复杂度:O(k)(此题k=2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution
{
public:
    int maxProfit(vector<int> &prices)
    {
        int k = 2;
        vector<int> res(k + 1, 0), cur(k + 1, 0);
        for(int i = 1; i < prices.size(); ++ i)
        {
            int diff = prices[i] - prices[i - 1];
            for(int j = k; j > 0; -- j)
            {
                cur[j] = max(res[j - 1] + (diff > 0 ? diff : 0), cur[j] + diff);
                res[j] = max(res[j], cur[j]);
            }
        }
        return res[k];
    }
};