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

Problem: Maximum profit from at most 2 buy-sell transactions (sell before buying again).

Problem: Maximum profit from at most 2 buy-sell transactions (sell before buying again).
def two(p):
    b1 = b2 = float('-inf'); s1 = s2 = 0
    for x in p:
        b1 = max(b1, -x); s1 = max(s1, b1 + x)
        b2 = max(b2, s1 - x); s2 = max(s2, b2 + x)
    return s2
print(two([2, 7, 1, 4, 9, 3, 8]))
What is printed?
  1. A. 18
  2. B. 12
  3. C. 8
  4. D. 13

Correct answer: D. 13

The best pair is buy 1 sell 9 (+8) and buy 3 sell 8 (+5) = 13 (2→7 plus 1→9 also gives 13). Unlimited transactions would give 18 by taking every rise; one transaction gives only 8.

More Coding Interview Problems questions

Exams that ask this topic