Maximize profit with transaction fee
Company: Coinbase
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Maximize profit with transaction fee states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= prices.length <= 5 * 10^4
- 1 <= prices[i] < 5 * 10^4 (when present)
- 0 <= fee < 5 * 10^4
- You may hold at most one share at a time and must sell before buying again.
Examples
Input: ([1, 3, 2, 8, 4, 9], 2)
Expected Output: 8
Explanation: Buy at 1, sell at 8 (profit 8-1-2=5), buy at 4, sell at 9 (profit 9-4-2=3). Total = 8.
Input: ([1, 3, 7, 5, 10, 3], 3)
Expected Output: 6
Explanation: Buy at 1, sell at 7 (7-1-3=3), buy at 5, sell at 10 (10-5-3=2)... the optimal single transaction buy at 1, sell at 10 gives 10-1-3=6, which beats splitting. Total = 6.
Hints
- Track two states each day: the best profit if you currently hold no share (cash), and the best profit if you currently hold one share (hold).
- Transition: cash = max(cash, hold + price - fee) models selling today (pay the fee on sell); hold = max(hold, cash - price) models buying today.
- Initialize cash = 0 and hold = -prices[0]. The answer is the final cash, because finishing without a held share never loses you anything.
- For empty input or strictly decreasing prices, no transaction is profitable, so the answer stays 0.