Maximize profit with transaction fees
Company: Coinbase
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates algorithm design skills, specifically understanding of dynamic programming and greedy strategies for optimizing profit under transaction fees, along with stateful decision-making and handling cost constraints.
Constraints
- 1 <= prices.length <= 5 * 10^4
- 1 <= prices[i] < 5 * 10^4
- 0 <= fee < 5 * 10^4
- An empty prices array returns 0.
Examples
Input: ([1, 3, 2, 8, 4, 9], 2)
Expected Output: 8
Explanation: Buy at 1, sell at 8 (5-2... net 5), buy at 4, sell at 9 (net 3): 5+3 = 8.
Input: ([1, 3, 7, 5, 10, 3], 3)
Expected Output: 6
Explanation: Buy at 1, sell at 10 (10-1-3 = 6). A single transaction beats splitting because each sale costs the fee.
Input: ([], 2)
Expected Output: 0
Explanation: Empty input: no transactions possible, profit is 0.
Input: ([5], 2)
Expected Output: 0
Explanation: Single day: you can never buy and sell, so profit is 0.
Input: ([9, 8, 7, 1], 1)
Expected Output: 0
Explanation: Strictly decreasing prices: no profitable transaction exists, so the best is to do nothing.
Input: ([1, 4, 6, 2, 8, 3, 10, 14], 3)
Expected Output: 13
Explanation: Buy at 1, sell at 6 (net 2), buy at 2, sell at 8 (net 3), buy at 3, sell at 14 (net 8): 2+3+8 = 13.
Hints
- Track two running states as you scan the days: the best net profit while holding no share (cash) and the best net profit while holding one share (hold).
- On each day, you can sell (cash = max(cash, hold + price - fee)) or buy (hold = max(hold, cash - price)). Subtract the fee once per completed sale.
- Initialize cash = 0 and hold = -prices[0], then iterate from day 1. The answer is cash at the end, since ending while holding a share is never better than having sold.