跳转至

买卖股票的最佳时机 IV⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
private:
    int maxProfit_k_inf(vector<int>& prices) {
        int n = prices.size();
        vector<vector<int>> dp(n, vector<int>(2));
        for (int i = 0; i < n; i++) {
            if (!i) {
                dp[i][0] = 0;
                dp[i][1] = -prices[i];
                continue;
            }
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
        }
        return dp[n - 1][0];
    }
public:
    int maxProfit(int k, vector<int>& prices) {
        int n = prices.size();
        // if (n <= 0) return 0;
        if (k > n / 2) return maxProfit_k_inf(prices);

        vector<vector<vector<int>>> dp(n, vector<vector<int>>(k + 1, vector<int>(2)));
        for (int i = 0; i < n; i++) {
            dp[i][0][1] = INT_MIN;
            dp[i][0][0] = 0;
        }

        for (int i = 0; i < n; i++) {
            for (int _k = k; _k >= 1; _k--) {
                if (!i) {
                    dp[i][_k][0] = 0;
                    dp[i][_k][1] = -prices[i];
                    continue;
                }
                dp[i][_k][0] = max(dp[i - 1][_k][0], dp[i - 1][_k][1] + prices[i]);
                dp[i][_k][1] = max(dp[i - 1][_k][1], dp[i - 1][_k - 1][0] - prices[i]);
            }
        }

        return dp[n - 1][k][0];
    }
};