leetcode 714. Best Time to Buy and Sell Stock with Transaction Fee

本文探讨了在无限次买卖股票并支付交易费的情况下,如何通过优化买卖时机来实现最大利润。介绍了动态规划方法,使用两个变量hold和cash来跟踪最佳交易状态,最终返回最大现金值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

Return the maximum profit you can make.

Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
Buying at prices[0] = 1
Selling at prices[3] = 8
Buying at prices[4] = 4
Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

还是买卖股票的问题,不同于122题,加了一个条件,就是可以无限次买卖一支股票,但是每次卖的时候要有手续费,在有手续费的情况下考虑最大收益

思路:
因为每次卖出要手续费,所以不能看到有收益就交易了

这里需要考虑较小点买入,较大点卖出,还有手续费

参考309的with cool down的思路dp。
dp的话本来是定义两个数组,但是为了节省space,只定义两个变量

定义一个hold,即较小点买入股票,持有股票的profit
一个cash,较大点卖出股票后转化的cash流,卖出的时候要减去手续费

持有的情况,hold[0] = -prices[0],因为要拿prices[0]的cash去买,所以收益就是-prices[0],后面再持续更新
cash[0]=0,刚开始买卖同一价格不仅没有profit,还会倒贴手续费,所以选择不交易,即0

hold:
买入股票的话相当于hold[i] = cash - prices[i]
不买的话保留hold[i - 1]
取两者较大的

cash:
卖出的话相当于hold[i] + prices[i] - fee
不交易的话就保留cash[i - 1]
取两者较大的

最后返回cash

    public int maxProfit(int[] prices, int fee) {
        if(prices ==null || prices.length == 0) {
            return 0;
        }
        
        int cash = 0;
        int hold = -prices[0];
        
        for (int i = 1; i < prices.length; i++) {
            cash = Math.max(cash, hold + prices[i] - fee);
            hold = Math.max(hold, cash - prices[i]);
        }
        
        return cash;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值