买卖股票的最佳时机 III
cpp
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int INF = 0x3f3f3f3f;
vector<vector<int>> f(n, vector<int>(3, -INF));
auto g = f;
g[0][0] = 0;
f[0][0] = -prices[0];
for (int i = 1; i < n; i++) {
for (int j = 0; j < 3; j++) {
f[i][j] = max(f[i - 1][j], g[i - 1][j] - prices[i]);
// 细节 如果不这样处理就会出现dp表第一列填表错误
g[i][j] = g[i - 1][j];
if (j > 0)
g[i][j] = max(g[i][j], f[i - 1][j - 1] + prices[i]);
}
}
int ret = 0;
for (int j = 0; j < 3; j++)
ret = max(ret, g[n - 1][j]);
return ret;
}
};
买卖股票的最佳时机 IV
cpp
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
int INF = 0x3f3f3f3f;
k = min(n / 2, k);
vector<vector<int>> f(n, vector<int>(k + 1, -INF));
auto g = f;
g[0][0] = 0;
f[0][0] = -prices[0];
for (int i = 1; i < n; i++) {
for (int j = 0; j < k + 1; j++) {
f[i][j] = max(f[i - 1][j], g[i - 1][j] - prices[i]);
g[i][j] = g[i - 1][j];
if (j > 0)
g[i][j] = max(g[i][j], f[i - 1][j - 1] + prices[i]);
}
}
int ret = 0;
for (int j = 0; j < k + 1; j++)
ret = max(ret, g[n - 1][j]);
return ret;
}
};