文章目录
- 买卖股票的最佳时机含冷冻期
- 买卖股票的最佳时机含手续费
买卖股票的最佳时机含冷冻期
分析:
class Solution {
public:int maxProfit(vector<int>& prices) {int n = prices.size();vector<vector<int>> dp(n, vector<int>(3));dp[0][0] = -prices[0];for (int i = 1; i < n; i++) {dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]);dp[i][1] = max(dp[i - 1][1], dp[i - 1][2]);dp[i][2] = dp[i - 1][0] + prices[i];}return max(dp[n - 1][1], dp[n - 1][2]);}
};
买卖股票的最佳时机含手续费
分析:
f[i]表示第i天后,是买入
状态
g[i]表示第i天后,是可买入
状态
class Solution {
public:int maxProfit(vector<int>& prices, int fee) {int n = prices.size();vector<int> f(n), g(n);f[0] = -prices[0] - fee;for (int i = 1; i < n; i++) {f[i] = max(g[i - 1] - prices[i] - fee, f[i - 1]);g[i] = max(f[i - 1] + prices[i], g[i - 1]);}return g[n - 1];}
};