算法训练第五十天

总结:今日是股票问题的变式,关键是要把握搞清楚dp数组的含义,自己也是被搞混了很久

188. 买卖股票的最佳时机 IV - 力扣(LeetCode)

代码:

class Solution {
public:
    int maxProfit(int k, vector& prices) {
        if(prices.size() == 1)
        return 0;
        int n = prices.size();
        vector> dp(n + 1,vector(2 * k,0));
        for(int i = 0;i < 2 * k;i = i + 2)
        {
            dp[1][i] = -prices[0];//持有
            dp[1][i + 1] = 0;//不持有
        }

        for(int i = 2;i <= n;i++)
        {
            for(int j = 0;j < 2 * k;j = j + 2)
            {
                if(j == 0)
                dp[i][j] = max(dp[i - 1][j],-prices[i - 1]);
                else
                dp[i][j] = max(dp[i - 1][j],dp[i - 1][j - 1]-prices[i - 1]);
                dp[i][j + 1] = max(dp[i - 1][j + 1],dp[i - 1][j] + prices[i - 1]);
            }
        }
        return dp[prices.size()][2 * k - 1];
    }
};

123. 买卖股票的最佳时机 III - 力扣(LeetCode)

class Solution {
public:
    int maxProfit(vector& prices) {
        if(prices.size() == 1 || prices.size() == 0)
        return 0;
        int n = prices.size();
        vector> dp(prices.size() + 1,vector(4,0));
        dp[1][0] = -prices[0];
        dp[1][1] = 0;
        dp[1][2] = -prices[0];
        dp[1][3] = 0;

        for(int i = 2;i <= prices.size();i++)
        {
            dp[i][0] = max(dp[i - 1][0],-prices[i - 1]);
            dp[i][1] = max(dp[i - 1][1],dp[i - 1][0] + prices[i - 1]);
            dp[i][2] = max(dp[i - 1][2],dp[i - 1][1] - prices[i - 1]);
            dp[i][3] = max(dp[i - 1][3],dp[i - 1][2] + prices[i - 1]);
        }
        return max(max(dp[n][0],dp[n][1]),max(dp[n][2],dp[n][3]));
    }
};

你可能感兴趣的:(算法)