LeetCode解题报告:714. Best Time to Buy and Sell Stock with Transaction Fee

Problem

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.

Note:

  1. 0 < prices.length <= 50000.
  2. 0 < prices[i] < 50000.
  3. 0 <= fee < 50000.
解题思路

  这一题乍一看上去真的不知道如何下手,因为是真的很麻烦,可以进行多笔交易,每一笔交易完成之后还要有手续费,完全没有头绪。实际上,这一题的基本解题思路是动态规划问题,因为我们可以发现,今天的获利和前一天是紧紧相关的,这就已经可以构成我们使用动态规划的方法的理由了。

  假设今天我需要买入股票,那么根据题意可以知道,前一天的状态必然是卖出的状态,要不然会有两支交易重叠。如果我今天需要卖出股票,那么前一天的状态必然是有股票在手的。考虑到这里,我们大概就已经知道如何去做了,我们需要维持两个数组,一个数组叫做 h o l d hold hold,表示已经买入的状态,另一个数组叫做 s o l d sold sold,表示卖出的状态,因此,我们的状态转移方程如下:

s o l d [ i ] = m a x ( h o l d [ i − 1 ] + p r i c e s [ i ] − f e e , s o l d [ i − 1 ] ) h o l d [ i ] = m a x ( s o l d [ i − 1 ] − p r i c e s [ i ] , h o l d [ i − 1 ] ) sold[i] = max(hold[i - 1] + prices[i] - fee, sold[i - 1]) \\ hold[i] = max(sold[i - 1] - prices[i], hold[i - 1]) sold[i]=max(hold[i1]+prices[i]fee,sold[i1])hold[i]=max(sold[i1]prices[i],hold[i1])

  以过了今天手上持有股票为例,如果我们来到了第 i i i天,那么我们有两个可能性,一个是前一天已经持有了股票,那么今天如果还要有股票在手的话,就只能保持不动,将前一天的状态顺延到今天,又或者可能是前一天没有股票,那么就在今天进行了买入的操作,因此状态和 s o l d [ i − 1 ] sold[i-1] sold[i1]相关。所以,我们在这两种情况中取获利最大的那种情况,即是到这一天为止的最佳获利。类似的,我们可以得到过了今天手上没有持有股票的情况,只不过不同的是,卖出股票的时候需要手续费。

   代码如下:(注意:第一天只能买入,不能卖出。)

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        sold = [0] * len(prices)
        hold = [0] * len(prices)
        
        hold[0] = -prices[0]
        
        for i in range(1, len(prices)):
            sold[i] = max(hold[i - 1] + prices[i] - fee, sold[i - 1])
            hold[i] = max(sold[i - 1] - prices[i], hold[i - 1])
        return sold[-1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值