题目来源:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/
C++题解1:动态规划。只要把买入股票的费用看成加上该费用加上手续费即可,其它与力扣 122. 买卖股票的最佳时机 II-CSDN博客 解法一致。
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size();
if(n <= 1) return 0;
// 状态0为持有股票,状态1为不持有股票
vector<vector<int>> dp(n, vector<int>(2, 0));
dp[0][0] = -prices[0] - fee;
for(int i = 1; i < n; i++){
dp[i][0] = max(dp[i-1][0], dp[i-1][1] - prices[i] - fee);
dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i]);
}
return dp[n-1][1];
}
};
C++题解2(来源代码随想录):贪心算法。情况一需要注意递增数组,避免手续费重复扣;就相当于进入该条件,下次循环还进入该条件。
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int result = 0;
int minPrice = prices[0]; // 记录最低价格
for (int i = 1; i < prices.size(); i++) {
// 情况二:相当于买入
if (prices[i] < minPrice) minPrice = prices[i];
// 计算利润,可能有多次计算利润,最后一次计算利润才是真正意义的卖出
if (prices[i] > minPrice + fee) {
result += prices[i] - minPrice - fee;
minPrice = prices[i] - fee; // 情况一,这一步很关键,避免重复扣手续费
}
}
return result;
}
};