← Recursion & DP

Micro-Drill #167 — Buy/Sell Stock with Fee

Recursion & DP Target: 10s

Two-state DP: cash (free to buy) and hold (free to sell). Fee paid on sell. No cooldown needed.

def maxProfit(prices, fee):
    cash = 0            # not holding
    hold = -prices[0]   # holding
    for p in prices[1:]:
        cash = max(cash, hold + p - fee)
        hold = max(hold, cash - p)
    return cash

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #166 Micro #168 →