思路:贪心。
手续费和买股票的价格放在一起考虑,第一次付了手续费,相当于下次就能免费买股票了,并且prices[i]为买的费用。
代码细节:遍历,如果比自己当前付出的钱 多,则卖出并且免手续费买了这支股票,否则更新手里的钱(即以更低的价格买股票)
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int ans = 0;
int buy = prices[0] + fee; //存买股票的最低价
for (const auto& each : prices) {
if (each > buy) {
ans += each - buy;
buy = each;
}
if (each + fee < buy) buy = each + fee;
}
return ans;
}
};