0714. Best Time to Buy and Sell Stock with Transaction Fee

Medium | Array + DP | 688 ms (75.06%), 21.1 MB (99.14%)

Source: LeetCode - Best Time to Buy and Sell Stock with Transaction Fee GitHub: Solution / Performance

You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.

Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

We can use Final State Machine to solve the series of these problems.

Note that this problem requires transaction fee after selling the stock.

  • Hold state means you hold the stock.

    • Since you don't have any stocks at the beginning, the profit at this state is initialized with negative infinity.

    • The profit in this state is calculated by: previous no-hold state's profit - current stock price (= buy)

  • No-Hold state means you do not hold any stocks.

    • Since you don't have any stocks at the beginning (you're initially at this state ), the profit at this state is initialized with 0.

    • The profit in this state is calculated by: previous hold state's profit + current stock price - fee (= sell)

    • Return the profit at the no-hold state as the maximum profit since the hold state still has stock on hold.

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        # (base case)
        if len(prices) == 0 or len(prices) == 1: return 0

        # ==================================================
        #  Array + Dynamic Programming              (FSM)  =
        # ==================================================
        # time  : O(n)
        # space : O(1)
        
        hold, noHold = float('-inf'), 0
        
        for price in prices:
            preHold, preNoHold = hold, noHold
            
            hold   = max(preHold,   preNoHold - price)
            noHold = max(preNoHold, preHold   + price - fee)
            
        return noHold

Last updated