[动态规划] leetcode 188 Best Time to Buy and Sell Stock IV

problem:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/

         以下这个答案超了内存限制orz,思路应该没啥问题,感觉要去评论区学一下花式优化技巧了。

         补充·,仔细看了一下卡空间复杂度的竟然是因为有个很大的K,但有效的K其实不会超过n / 2 (n : prices长度),因此首先需要限制K的大小,其次是n + 1的空间也是冗余的。

class Solution {
public:
    int maxProfit(int K, vector<int>& prices) {
        int n = prices.size();
        vector<vector<int>> hasStock(n + 1, vector<int>(K + 1, 0));
        vector<vector<int>> noStock(n + 1, vector<int>(K + 1, 0));
        int res = 0;
        
        for (int k = 0; k <= K; k++)
        {
            hasStock[0][k] = -500000;
        }
        for (int k = 1; k <= K; k++)
        {
            for(int i = 0;i < n;i++)
            {
                hasStock[i + 1][k] = max(hasStock[i][k], noStock[i][k - 1] - prices[i]);
                noStock[i + 1][k] = max(noStock[i][k], hasStock[i][k] + prices[i]);
            }
            res = max(noStock[n][k], res);
        }
        return res;
    }
};

 优化后:

class Solution {
public:
    int maxProfit(int K, vector<int>& prices) {
        int n = prices.size();
        int res = 0;
        K = min(K, n / 2);
        vector<int> hasStock(K + 1, 0);
        vector<int> noStock(K + 1, 0);

        for (int k = 0; k <= K; k++)
        {
            hasStock[k] = -500000;
        }

        for (int i = 0; i < n; i++)
        {
            for (int k = 1; k <= K; k++)
            {
                int has = hasStock[k];
                int no = noStock[k];
                hasStock[k] = max(has, noStock[k - 1] - prices[i]);
                noStock[k] = max(no, has + prices[i]);

                res = max(noStock[k], res);
            }
        }

        return res;
    }
};

 

posted @ 2019-08-07 11:39  fish1996  阅读(147)  评论(0编辑  收藏  举报