Bootstrap

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

原题链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/submissions/
每一卖出股票就会额外付出一定的手续费。此题的思路和最佳买卖股票时机含冷冻期的思路类似。
建立动态规划的递归方程。
每一天有两个状态,卖出,买入。
第i天的状态有:sell, buy
则第i-1天的状态有:presell, prebuy
递归方程为:
buy = max(prebuy, presell - prices[i])
sell = max(presell, prebuy + prices[i] - fee)

class Solution:
    def maxProfit(self, prices, fee):
        """
        :type prices: List[int]
        :type fee: int
        :rtype: int
        """
        n = len(prices)
        if n<2:
            return 0
        buy = -prices[0]; sell = 0
        for i in range(1,n):
            buy = max(buy, sell - prices[i])
            sell = max(sell, buy + prices[i] - fee)
        return sell
;