Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Trade a stock any number of times (one share at most), but after selling you must wait one day before buying again.

Problem: Trade a stock any number of times (one share at most), but after selling you must wait one day before buying again.
def profit(p):
    hold, sold, rest = float('-inf'), 0, 0
    for x in p:
        hold, sold, rest = max(hold, rest - x), hold + x, max(rest, sold)
    return max(sold, rest)
print(profit([3, 1, 4, 8, 2, 5, 9, 1, 6]))
What is printed?
  1. A. 19
  2. B. 12
  3. C. 14
  4. D. 11

Correct answer: B. 12

Three states: holding, just sold (cooldown next day) and resting. Unlimited trading without cooldown would collect every rise: 3 + 4 + 3 + 4 + 5 = 19. With the cooldown the best is buy at 1 and sell at 8 (+7), then buy at 1 and sell at 6 (+5) = 12; taking the 2 → 9 rise as well is impossible, and 1→8 plus 5→9 gives only 11.

More Coding Interview Problems questions

Exams that ask this topic