代码随想录算法训练营第49天|123.买卖股票的最佳时机III ● 188.买卖股票的最佳时机IV

  123.买卖股票的最佳时机III

//#define N 5
class Solution {
public:
    int maxProfit(vector& prices) {
        vector dp(5, 0);
        //dp[0] = 0//没买入持有现金
        dp[1] = -prices[0];//第一次买入持有现金
        //dp[2] = 0//第一次卖出持有现金
        dp[3] = -prices[0];//第二次买入持有现金
        //dp[4] = 0//第二次卖出持有现金
        for (int i = 1; i < prices.size(); i++) {
        //dp[0] = dp[0];
        int tmp1 = dp[1];
        int tmp2 = dp[2];
        int tmp3 = dp[3];
        dp[1] = max(dp[1], dp[0] - prices[i]);
        dp[2] = max(dp[2], tmp1 + prices[i]);
        dp[3] = max(dp[3], tmp2 - prices[i]);
        dp[4] = max(dp[4], tmp3 + prices[i]);
        }
        return dp[4];
    }
};

188.买卖股票的最佳时机IV

class Solution {
public:
    int maxProfit(int k, vector& prices) {
        int len = 2 * k + 1;
        vector> dp(2, vector(len, 0));
        for (int i = 1; i < len; i += 2) {
            dp[0][i] = -prices[0];
        }
        for (int i = 1; i < prices.size(); i++) {
            int j = i % 2;
            int j_pre = (i + 1) % 2;
            for (int k = 1; k < len; k += 2) {
                //cout << k << endl;
                dp[j][k] = max(dp[j_pre][k], dp[j_pre][k - 1] - prices[i]);
                dp[j][k + 1] = max(dp[j_pre][k + 1], dp[j_pre][k] + prices[i]);
            }
        }
        return max(dp[1][len - 1], dp[0][len - 1]);
    }
};

你可能感兴趣的:(代码随想录算法训练营,算法,动态规划,leetcode)