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?
  1. A. 94
  2. B. 120
  3. C. 115
  4. 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

Exams that ask this topic