2023.8.21
这道题是 买卖股票的最佳时机III 的升级版,即买卖次数限制为k次,做法和上一篇如法炮制,直接看代码:
class Solution {
public:int maxProfit(int k, vector<int>& prices) {vector<vector<int>> dp(prices.size(),vector<int>(k*2));//初始化,偶数为持股,奇数为不持股for(int i=0; i<k*2; i++){if(i % 2 == 0) dp[0][i] = -prices[0];else dp[0][i] = 0;}// 遍历for(int i=1; i<prices.size(); i++){dp[i][0] = max(dp[i-1][0] , -prices[i]);for(int j=1; j<k*2; j++){if(j % 2 == 0) dp[i][j] = max(dp[i-1][j] , dp[i-1][j-1]-prices[i]); // 偶数为持股状态else dp[i][j] = max(dp[i-1][j] , dp[i-1][j-1]+prices[i]);}}return dp[prices.size()-1][k*2-1];}
};