class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
vector<vector<int>> dp(prices.size(), vector<int>(2 * k + 1, 0));
for (int j = 1; j <= 2 * k; j++) {
if (j % 2 != 0)
dp[0][j] = -prices[0];
else
dp[0][j] = 0;
}
int maxProfit = 0;
for (int i = 1; i < prices.size(); i++) {
for (int j = 1; j < 2 * k + 1; j++) {
if (j % 2 != 0) {
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1] - prices[i]);
if (dp[i][j] > maxProfit)
maxProfit = dp[i][j];
}
else {
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1] + prices[i]);
if (dp[i][j] > maxProfit)
maxProfit = dp[i][j];
}
}
}
return maxProfit;
}
};
LeetCode188.买卖股票的最佳时机IV
最新推荐文章于 2024-09-14 22:25:23 发布