LeetCode:714. 买卖股票的最佳时机含手续费(python)

LeetCode:714. 买卖股票的最佳时机含手续费(python)

给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。

你可以无限次地完成交易,但是你每次交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。

返回获得利润的最大值。

示例 1:

输入: prices = [1, 3, 2, 8, 4, 9], fee = 2
输出: 8
解释: 能够达到的最大利润:
在此处买入 prices[0] = 1
在此处卖出 prices[3] = 8
在此处买入 prices[4] = 4
在此处卖出 prices[5] = 9
总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

注意:

  • 0 < prices.length <= 50000.
  • 0 < prices[i] < 50000.
  • 0 <= fee < 50000.

LeetCode 链接


思路:
分析股票交易动态规划方案 见该博客的思路2 模块1,本题在其基础上进行扩展。
  • 原动态转移方程

    dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i])
    max( 选择 rest , 选择 sell )

    dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i])
    max( 选择 rest , 选择 buy )

  • 本题加入交易时需要手续费的条件,因此更改动态转移方程如下:

    dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])

    dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i] - fee)

    说明

    • dp[i][1]-fee 相当于买入的价格提高了(若从 i=1 处开始迭代,注意初始化处也要减去相应的手续费)
    • dp[i][0]-fee 相当于卖处的利润减小了(效果相同)
附代码(Python3):
class Solution:
    def maxProfit(self, prices, fee):
        if not prices:
            return 0
        
        dp_i_0, dp_i_1 = 0, float('-inf')
        for i in range(len(prices)):
            dp_i_0 = max(dp_i_0, dp_i_1+prices[i])
            dp_i_1 = max(dp_i_1, dp_i_0-prices[i]-fee)
        return dp_i_0
prices = [1, 3, 2, 8, 4, 9]
fee = 2

test = Solution()
test.maxProfit(prices, fee)
8

总结:其他股票题的笔记如下

LeetCode:121. 买卖股票的最佳时机(python)

LeetCode:122. 买卖股票的最佳时机 II(python)

LeetCode:123. 买卖股票的最佳时机 III(python)

LeetCode:188. 买卖股票的最佳时机 IV(python)

LeetCode:309. 最佳买卖股票时机含冷冻期(python)

LeetCode:714. 买卖股票的最佳时机含手续费(python)


参考:

LeetCode 题解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值