KatInterview

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

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the maximum profit from buying and selling a stock, where we can perform as many transactions as we like. The constraints are that we cannot hold more than one share at a time, and each complete transaction (a buy and a sell) incurs a fixed fee.

Solution

Best Time to Buy and Sell Stock with Transaction Fee in Python

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        n = len(prices)
        # If there are fewer than 2 days, no transaction is possible.
        if n < 2:
            return 0
        
        # `cash`: max profit if we have no stock at the end of the day.
        cash = 0
        # `hold`: max profit if we have one stock at the end of the day.
        # On day 0, if we hold a stock, we must have bought it.
        hold = -prices[0]
        
        # Iterate from the second day.
        for i in range(1, n):
            # We need the previous day's cash to calculate the new hold state.
            # Store it in a temporary variable before it's updated.
            prev_cash = cash
            
            # Update cash state for day i:
            # max of (resting with cash, or selling stock from previous hold state).
            cash = max(cash, hold + prices[i] - fee)
            
            # Update hold state for day i:
            # max of (resting with stock, or buying stock from previous cash state).
            hold = max(hold, prev_cash - prices[i])

        # The maximum profit at the end must be when we have no stock.
        return cash

Best Time to Buy and Sell Stock with Transaction Fee in Java

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int n = prices.length;
        // If there are fewer than 2 days, no transaction is possible.
        if (n < 2) {
            return 0;
        }

        // `cash` represents the maximum profit if we end the day with no stock.
        int cash = 0;
        // `hold` represents the maximum profit if we end the day holding a stock.
        // On day 0, if we hold a stock, we must have bought it, so profit is -prices[0].
        int hold = -prices[0];

        // Iterate from the second day.
        for (int i = 1; i < n; i++) {
            // We need the previous day's cash to calculate the new hold state.
            // Store it in a temporary variable before it's updated.
            int prevCash = cash;

            // Update cash state for day i:
            // max of (resting with cash, or selling stock from previous hold state)
            cash = Math.max(cash, hold + prices[i] - fee);

            // Update hold state for day i:
            // max of (resting with stock, or buying stock from previous cash state)
            hold = Math.max(hold, prevCash - prices[i]);
        }

        // On the last day, profit is maximized by not holding any stock.
        return cash;
    }
}

Best Time to Buy and Sell Stock with Transaction Fee in C++

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int n = prices.size();
        // If there are fewer than 2 days, no transaction is possible.
        if (n < 2) {
            return 0;
        }

        // `cash` represents the maximum profit on day `i` if we don't hold a stock.
        int cash = 0;
        // `hold` represents the maximum profit on day `i` if we hold a stock.
        // On day 0, if we hold a stock, we must have bought it, so profit is -prices[0].
        int hold = -prices[0];

        // Iterate from the second day.
        for (int i = 1; i < n; ++i) {
            // We need the previous day's cash to calculate the new hold state.
            // Store it in a temporary variable before it's updated.
            int prev_cash = cash;

            // Update cash state for day i.
            // We can either continue having cash from day i-1 (profit `cash`),
            // or sell the stock we held on day i-1 (profit `hold + prices[i] - fee`).
            cash = max(cash, hold + prices[i] - fee);

            // Update hold state for day i.
            // We can either continue holding from day i-1 (profit `hold`),
            // or buy today after having cash on day i-1 (profit `prev_cash - prices[i]`).
            hold = max(hold, prev_cash - prices[i]);
        }

        // The maximum profit at the end must be when we have no stock.
        return cash;
    }
};

Best Time to Buy and Sell Stock with Transaction Fee in TypeScript

function maxProfit(prices: number[], fee: number): number {
    const n = prices.length;
    // If there are fewer than 2 days, no transaction is possible.
    if (n < 2) {
        return 0;
    }

    // `cash` represents the maximum profit if we end the day with no stock.
    let cash = 0;
    // `hold` represents the maximum profit if we end the day holding a stock.
    // On day 0, if we hold a stock, we must have bought it, so profit is -prices[0].
    let hold = -prices[0];

    // Iterate from the second day.
    for (let i = 1; i < n; i++) {
        // We need the previous day's cash to calculate the new hold state.
        // Store it in a temporary variable before it's updated.
        const prevCash = cash;

        // Update cash state for day i:
        // max of (resting with cash, or selling stock from previous hold state)
        cash = Math.max(cash, hold + prices[i] - fee);

        // Update hold state for day i:
        // max of (resting with stock, or buying stock from previous cash state)
        hold = Math.max(hold, prevCash - prices[i]);
    }

    // On the last day, profit is maximized by not holding any stock.
    return cash;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.