Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Burst balloons; bursting balloon i earns left × a[i] × right using its current neighbours (1 beyond the ends). Maximise the total.
Problem: Burst balloons; bursting balloon i earns left × a[i] × right using its current neighbours (1 beyond the ends). Maximise the total.
def burst(a):
b = [1] + a + [1]; n = len(b)
dp = [[0] * n for _ in range(n)]
for gap in range(2, n):
for l in range(n - gap):
r = l + gap
dp[l][r] = max(dp[l][k] + dp[k][r] + b[l] * b[k] * b[r] for k in range(l + 1, r))
return dp[0][n - 1]
print(burst([2, 4, 3, 5]))What is printed?- A. 94
- B. 120
- C. 115
- D. 136
Correct answer: C. 115
The trick is to choose the LAST balloon k to burst in (l, r): its neighbours are then exactly b[l] and b[r], which makes the two sides independent. The interval DP gives 115, the same as trying all 24 bursting orders.
More Coding Interview Problems questions
- Problem: Count the ways to split s into a sequence of dictionary words. python def count(s, words): W = set(words); dp = [1] + [0] len(s)…
- Problem: Regular-expression matching where '.' matches any one character and 'x' matches zero or more x (the whole string must match)…
- Problem: Count how many distinct index sequences of s spell t as a subsequence. python def distinct(s, t): dp = [1] + [0] len(t) for c in…
- Problem: Maximum profit from at most 2 buy-sell transactions (sell before buying again). python def two(p): b1 = b2 = float('-inf'); s1 =…
- 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…