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?- A. 18
- B. 12
- C. 8
- 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
- Problem: A courier starts at depot 0, must visit every city exactly once and return to 0. Solve it with bitmask DP (Held–Karp). python INF…
- Problem: Sum a[i] XOR a[j] over all pairs i < j in O(n · bits) by counting, for each bit, how many numbers have it set. python def…
- Edge case: nCr mod p is computed with factorials and Fermat inverses. Here n ≥ p. python p = 7 fact = [1] 11 for i in range(1, 11)…
- Problem: Extended Euclid returns g = gcd(a, b) and integers x, y with a·x + b·y = g. python def eg(a, b): if b == 0: return a, 1, 0 g, x…
- Problem: A segment tree with lazy propagation supports 'add v to a[l..r]' and 'sum of a[l..r]' on an array of 8 zeros. python N = 8 t, lz…
- Problem: Count inversions (i < j, a[i] > a[j]) with a Fenwick tree over values, scanning from the right. python def inversions(a): n =…