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

1. 题目描述

给定一个整数数组 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.

2. 思路

大致思路和股票问题系列第二题类似:买卖股票的最佳时机||
因为有手续费,因此我们假设当买入股票的时候,需要支付费用。那么状态之间的转换方程,需要进行改变:
在这里插入图片描述
由于股票交易次数不限制,因此不需要考虑k和k-1的问题。

2.1 代码

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        if len(prices) == 0:
            return 0
        n = len(prices)
        dp_i_0 = 0
        dp_i_1 = -prices[0]-fee
        for i in range(1,n):
            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

猜你喜欢

转载自blog.csdn.net/ggdhs/article/details/92782092