The "Best Time to Buy and Sell Stock with Transaction Fee interview question" adds a "tax" to your trading. You can make as many transactions as you want, but every time you sell, you must pay a fixed transaction fee. This fee discourages frequent trading unless the profit from a specific transaction is large enough to cover the cost.
Citadel and Bloomberg ask the "Best Time to Buy and Sell Stock with Transaction Fee coding problem" to see if a candidate can adapt a greedy mindset to include costs. It tests whether you can identify that a transaction is only "worth it" if the price increase exceeds the fee. It is a fundamental test of "Dynamic Programming" and "Greedy" logic.
This is solved using a Two-State Dynamic Programming approach.
hold[i]: Max profit on day if you currently own a stock.
hold[i] = max(hold[i-1], free[i-1] - prices[i])free[i]: Max profit on day if you do not own a stock.
free[i] = max(free[i-1], hold[i-1] + prices[i] - fee)
Notice that the fee is subtracted only when selling. Alternatively, you can subtract it when buying.Prices: [1, 3, 2, 8, 4, 9], Fee: 2
hold = -1, free = 0.free = max(0, -1 + 3 - 2) = 0. (No gain after fee).free = max(0, -1 + 8 - 2) = 5.hold = max(-1, 5 - 4) = 1. (Better to "reset" the buy at price 4).free = max(5, 1 + 9 - 2) = 8.
Max Profit: 8.prices[i] - prices[i-1] (like Stock II) and then subtracting the fee at the very end.hold and free values are needed ( space).Cost-based optimization problems are common in fintech. Practice reducing space complexity by observing that you only need the previous state. This "Array interview pattern" optimization is always a bonus in the eyes of an interviewer.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Jump Game II | Medium | Solve | |
| Best Time to Buy and Sell Stock II | Medium | Solve | |
| Jump Game | Medium | Solve | |
| Maximum Length of Subarray With Positive Product | Medium | Solve | |
| Wiggle Subsequence | Medium | Solve |