Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Buy and sell a stock any number of times with a one-day cooldown after each sale. Maximise profit.

Problem: Buy and sell a stock any number of times with a one-day cooldown after each sale. Maximise profit.
def cooldown(p):
    hold, sold, rest = -p[0], 0, 0
    for x in p[1:]:
        hold, sold, rest = max(hold, rest - x), hold + x, max(rest, sold)
    return max(sold, rest)
print(cooldown([1, 2, 3, 0, 2]), cooldown([1, 2, 4]))
What is printed?
  1. A. 4 3
  2. B. 3 2
  3. C. 3 3
  4. D. 2 3

Correct answer: C. 3 3

State machine: hold (own a share), sold (sold today), rest (free to buy). Buy at 1, sell at 2, cool down on 3, buy at 0, sell at 2: 1 + 2 = 3. Without cooldown it would be 2 + 2 = 4. [1, 2, 4] → buy 1, sell 4 = 3. O(n), O(1).

More Coding Interview Problems questions

Exams that ask this topic