代码随想录算法训练营第五十一天| 309.最佳买卖股票时机含冷冻期、714.买卖股票的最佳时机含手续费
309.最佳买卖股票时机含冷冻期
题目链接
文章讲解
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
vector<int> dp(3);
dp[0] = -prices[0];
dp[1] = 0;
dp[2] = 0;
for (int i = 1; i < n; i++) {
int tmp1 = dp[0], tmp2 = dp[1], tmp3 = dp[2];
dp[0] = max(tmp1, tmp2 - prices[i]);
dp[1] = max(tmp2, tmp3);
dp[2] = tmp1 + prices[i];
}
return max(dp[1], dp[2]);
}
};
714.买卖股票的最佳时机含手续费
题目链接
文章讲解
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size();
vector<int> dp(2);
dp[0] = -prices[0];
dp[1] = 0;
for (int i = 1; i < prices.size(); i++) {
int tmp1 = dp[0], tmp2 = dp[1];
dp[0] = max(tmp1, tmp2 - prices[i]);
dp[1] = max(tmp2, tmp1 + prices[i] -fee);
}
return dp[1];
}
};