Maximize stock profit with constraints
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
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 stock profit with constraints states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
- 0 <= fee <= 10^4
- At most two complete transactions (buy then sell); you hold at most one share at a time.
- After any sell on day i, buying is forbidden on day i + 1 (one-day cooldown).
- Each completed sale subtracts `fee` from its proceeds.
- Required: O(n) time and O(1) additional space.
- Return 0 when no profitable sequence of trades exists.
Examples
Input: ([3, 3, 5, 0, 0, 3, 1, 4], 0)
Expected Output: 6
Explanation: fee=0. Buy at 0 (day 3), sell at 3 (day 5) -> +3; cooldown day 6, buy at 1 (day 6) is the cooldown day so skip, buy at 1 on day 6 forbidden; instead buy at 0 (day 4) sell at 3 (day 5), then buy at 1 (day 6) sell at 4 (day 7). Best two cooldown-separated trades total 6.
Input: ([1, 2, 3, 4, 5], 0)
Expected Output: 4
Explanation: fee=0, strictly increasing. One transaction buy at 1, sell at 5 captures the entire +4 run; splitting it would force a cooldown gap that loses value, so 4 is optimal.
Hints
- Track four running states as you sweep the prices once: the best profit while holding the 1st share (buy1), after completing the 1st sale (sell1), while holding the 2nd share (buy2), and after the 2nd sale (sell2).
- The cooldown only matters between the first sale and the second buy. Buy the 2nd share using the value of sell1 from *yesterday*, not today, so a buy can never sit on the day immediately after a sale.
- Apply the `fee` at the moment of each sell: sell transitions use `+ price - fee`. Buy transitions use `- price`.
- The answer is max(0, sell1, sell2): zero transactions is always allowed, and one transaction may beat two when the fee or cooldown eats the second trade's margin.