SDE & MLE Prep

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

Problem

prices[i] is a stock's price on day i. Make as many transactions as you like (holding at most one share at a time), paying fee for each one. Return the maximum profit.

Example: prices = [1,3,2,8,4,9], fee = 2 → 8 (buy 1, sell 8; buy 4, sell 9)

Constraints: n ≤ 5·10⁴.

Two states: hold and cash. cash = max(cash, hold + p − fee), hold = max(hold, cash − p).

Complexity: O(n) time, O(1) space.

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        cash, hold = 0, -prices[0]
        for p in prices[1:]:
            cash = max(cash, hold + p - fee)
            hold = max(hold, cash - p)
        return cash