题目链接:Best Time to Buy and Sell Stock IV

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 k transactions.

Note:

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

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

Best Time to Buy and Sell StockBest Time to Buy and Sell Stock IIBest Time to Buy and Sell Stock III类似的题目,这次是进一步升级了。

其实在第三道题的时候,就已经将问题扩展到k次了,因此可以直接采用该思路。

然而,会有一个问题,就是当k大于数组大小一半的时候,就会出现一定问题:申请数组太大,可能会出现Runtime Error。可以注意到当k大于数组大小一半的时候,就可以随意进行买入卖出了,相当于次数不限(因为永远不会达到k次),因此该情形和第二道题相同了,问题得以解决。

时间复杂度:O(nk)

空间复杂度:O(k)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution
{
public:
    int maxProfit(int k, vector<int> &prices)
    {
        if(k > prices.size() / 2)
            return maxProfit_most(prices);
        else
            return maxProfit_k(k, prices);
    }
private:
    // 买入卖出次数不限
    int maxProfit_most(vector<int> &prices)
    {
        int res = 0;
        for(int i = 1; i < prices.size(); ++ i)
            res += max(0, prices[i] - prices[i - 1]);
        return res;
    }
    // 最多允许k次买入卖出
    int maxProfit_k(int k, vector<int> &prices)
    {
        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];
    }
};