← Back to Algorithms, page 5

algorithms-0089 · Hard senior

Burst balloons: maximise the coins earned by bursting all balloons, where bursting one pays the product of it and its current neighbours, using interval DP.

Pad the array with 1 at both ends. Let dp[l][r] be the best total for bursting every balloon strictly between l and r. Choose k as the last balloon burst in that interval: it then pays a[l] * a[k] * a[r], and the two sides are independent subproblems. dp[l][r] = max over k of dp[l][k] + a[l] * a[k] * a[r] + dp[k][r]. O(n^3) time and O(n^2) space.

Full answer

Problem

Given balloons with values nums, bursting balloon i earns left * nums[i] * right, where left and right are the current neighbours (or 1 past the ends). After bursting, neighbours become adjacent. Return the maximum coins from bursting all balloons.

Example: [3, 1, 5, 8] returns 167: burst 1 (315 = 15), then 5 (358 = 120), then 3 (138 = 24), then 8 (181 = 8).

Constraints: 1 <= n <= 300, values from 0 to 100.

Brute force

Try every bursting order: n! orders. Memoizing on the remaining tuple of balloons helps but still has 2^n states, as in the test reference.

Optimal approach

  1. a = [1] + nums + [1], size m = n + 2.
  2. dp[l][r] = best coins from bursting all balloons strictly between l and r (open interval); dp[l][l+1] = 0.
  3. For gap from 2 to m - 1, for each l with r = l + gap: dp[l][r] = max(dp[l][k] + a[l] * a[k] * a[r] + dp[k][r]) for k in l + 1..r - 1.
  4. Answer: dp[0][m-1].

Why it works

Choosing the first balloon to burst does not split the problem, because its neighbours change afterwards. Choosing the last balloon k in the interval does: while everything else between l and r is being burst, k is still present, so it acts as a fixed wall between the left part (l, k) and the right part (k, r). Those two parts never interact, and when k is finally burst its neighbours are exactly a[l] and a[r]. Trying every k as the last one covers all orders.

Complexity

O(n^3) time (about n^3 / 6 inner steps for n = 300, roughly 4.5 million, fine in Python) and O(n^2) space.

Code

python
import random
from functools import lru_cache


def max_coins(nums):
    """Burst balloons: bursting i earns left * nums[i] * right with current neighbours.
    Interval DP on which balloon is burst LAST inside (l, r). O(n^3) time, O(n^2) space."""
    a = [1] + [x for x in nums] + [1]
    n = len(a)
    dp = [[0] * n for _ in range(n)]       # dp[l][r]: best for balloons strictly between l and r
    for gap in range(2, n):
        for l in range(0, n - gap):
            r = l + gap
            best = 0
            for k in range(l + 1, r):      # k is the last balloon burst between l and r
                best = max(best, dp[l][k] + a[l] * a[k] * a[r] + dp[k][r])
            dp[l][r] = best
    return dp[0][n - 1]


def brute(nums):
    """Try every bursting order, memoised on the remaining tuple."""
    @lru_cache(maxsize=None)
    def go(rest):
        if not rest:
            return 0
        best = 0
        for i in range(len(rest)):
            left = rest[i - 1] if i > 0 else 1
            right = rest[i + 1] if i + 1 < len(rest) else 1
            best = max(best, left * rest[i] * right + go(rest[:i] + rest[i + 1:]))
        return best
    return go(tuple(nums))


if __name__ == "__main__":
    assert max_coins([3, 1, 5, 8]) == 167
    assert max_coins([1, 5]) == 10
    assert max_coins([]) == 0 and max_coins([7]) == 7
    rng = random.Random(89)
    for _ in range(300):
        a = [rng.randint(0, 9) for _ in range(rng.randint(0, 7))]
        assert max_coins(a) == brute(a)
    print("all tests passed")

Save as b89_burst_balloons.py and run python3 b89_burst_balloons.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty array (0). One balloon (its value). Zero-valued balloons (still need correct neighbour handling; some solutions remove them first, which is safe because bursting a 0 contributes 0 and they never help as neighbours). Large n where O(n^3) in a slow language needs care.

Pattern

Interval DP with a "last action splits the interval" insight. The same idea solves matrix chain multiplication, minimum cost to cut a stick, optimal binary search tree, polygon triangulation and merging stones. When the first choice does not separate subproblems, try the last.

python
import random
from functools import lru_cache


def max_coins(nums):
    """Burst balloons: bursting i earns left * nums[i] * right with current neighbours.
    Interval DP on which balloon is burst LAST inside (l, r). O(n^3) time, O(n^2) space."""
    a = [1] + [x for x in nums] + [1]
    n = len(a)
    dp = [[0] * n for _ in range(n)]       # dp[l][r]: best for balloons strictly between l and r
    for gap in range(2, n):
        for l in range(0, n - gap):
            r = l + gap
            best = 0
            for k in range(l + 1, r):      # k is the last balloon burst between l and r
                best = max(best, dp[l][k] + a[l] * a[k] * a[r] + dp[k][r])
            dp[l][r] = best
    return dp[0][n - 1]


def brute(nums):
    """Try every bursting order, memoised on the remaining tuple."""
    @lru_cache(maxsize=None)
    def go(rest):
        if not rest:
            return 0
        best = 0
        for i in range(len(rest)):
            left = rest[i - 1] if i > 0 else 1
            right = rest[i + 1] if i + 1 < len(rest) else 1
            best = max(best, left * rest[i] * right + go(rest[:i] + rest[i + 1:]))
        return best
    return go(tuple(nums))


if __name__ == "__main__":
    assert max_coins([3, 1, 5, 8]) == 167
    assert max_coins([1, 5]) == 10
    assert max_coins([]) == 0 and max_coins([7]) == 7
    rng = random.Random(89)
    for _ in range(300):
        a = [rng.randint(0, 9) for _ in range(rng.randint(0, 7))]
        assert max_coins(a) == brute(a)
    print("all tests passed")

Open-interval DP over a padded array, checked against an exhaustive memoized search over remaining balloons.

Complexity

Time: O(n^3). Space: O(n^2). Knuth-style speed-ups do not apply directly here; the cubic bound is standard.

By level

Fresher: Understands why trying all orders is too slow and follows the last-burst idea on a 3-balloon example. Fills a small table with guidance.

Mid: Writes the interval DP with padding and open intervals and explains the independence of the two sides. Recovers the order from choices.

Senior: Recognizes the last-action split across interval DP problems such as matrix chains and stick cutting, and explains when optimizations like Knuth's apply. Discusses reducing constant factors for n in the hundreds.

Key points

  • Pad with 1 at both ends
  • dp over open intervals (l, r)
  • Choose the last balloon burst, not the first
  • The last balloon's neighbours are a[l] and a[r]
  • O(n^3)

Common mistakes

  • Choosing the first balloon to burst and getting dependent subproblems
  • Using closed intervals and mixing up neighbour values
  • Wrong fill order by interval length
  • Forgetting the padding

Follow-ups

  • How does matrix chain multiplication use the same idea?
  • How would you recover the bursting order?
  • What changes if bursting pays only left * right?

Tips

  • Explain why the first choice fails
  • Define the interval as open
  • Fill by increasing gap

Evaluation rubric

  • Correct last-choice insight
  • Correct recurrence and fill order
  • Correct complexity
  • Edge cases