力扣 714. 买卖股票的最佳时机含手续费

题目来源: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;
    }
};

  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值