这段代码的问题在于对于交易次数的计算有误。在第二个for循环中,对于每个时间点i和每个交易次数t,如果i是奇数,表示当前是买入状态,应该从前一个时间点的t-1次交易中买入,而不是从前一个时间点的t次交易中买入。同理,如果i是偶数,表示当前是卖出状态,应该从前一个时间点的t-1次交易中卖出,而不是从前一个时间点的t次交易中卖出。所以需要修改代码如下:

class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        vector<vector<int>> dp(prices.size(), vector<int>(2*k+1, 0));
        dp[0][0] = 0;
        for (int i = 1; i <= 2*k; i++) {
            if (i % 2) {
                dp[0][i] = -prices[0];
            }
        }
        for (int i = 1; i < prices.size(); i++) {
            dp[i][0] = 0;
            for (int t = 1; t < 2*k+1; t++) {
                if (t % 2) {
                    dp[i][t] = max(dp[i-1][t-1]-prices[i], dp[i-1][t]);
                } else {
                    dp[i][t] = max(dp[i-1][t-1]+prices[i], dp[i-1][t]);
                }
            }
        }
        return dp[prices.size()-1][2*k];
    }
};
LeetCode 188. Best Time to Buy and Sell Stock IV - 错误分析及代码修正

原文地址: https://www.cveoy.top/t/topic/qgnn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录