15% off all plans & roadmaps Use code

See plans

Burst Balloons

Updated

TL;DR: Burst every balloon to maximize coins, where each burst pays the product of the balloon and its current neighbors. Choose which balloon bursts last in each interval, which makes the subproblems independent and gives an O(n^3) interval DP.

Problem

You are given n balloons indexed from 0 to n - 1. Each balloon has a number painted on it, given by the array nums. You must burst every balloon.

Bursting balloon i earns nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 falls outside the array, treat that neighbor as a balloon painted with 1. After a balloon bursts, it is removed and its neighbors become adjacent.

Return the maximum number of coins you can collect by choosing the order of bursts well.

Example 1

Input: nums = [3,1,5,8]
Output: 167
Explanation: [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [], and the coins are 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167.

Example 2

Input: nums = [1,5]
Output: 10

Constraints

  • n == nums.length
  • 1 <= n <= 300
  • 0 <= nums[i] <= 100

Constraints that matter

  • n up to 300 rules out trying every burst order. 300 factorial is far beyond any limit, and even 2^300 subsets are impossible.
  • n up to 300 allows O(n^3). That is about 4.5 million (left, last, right) triples, which runs in well under a second.
  • A 2D table of about 302 x 302 ints is tiny, so O(n^2) memory is no concern.
  • Values up to 100 give at most 100^3 = 10^6 coins per burst. The total stays near 3 * 10^8 at most, so a 32-bit int holds it.
  • Values can be 0, so a burst can pay nothing. Zeros are harmless to the DP and can be removed up front as a shortcut.

View on LeetCode

Hints

Hint 1

This is interval DP.

Hint 2

Try every balloon as the next one to burst, collect its coins, remove it, and recurse on what is left.

Solution

Intuition

This is interval DP. The natural question is which balloon to burst first, but that choice breaks the problem. When you burst balloon k first, its two neighbors become adjacent. The left part and the right part now depend on each other, so you cannot solve them separately.

Picture a row of fence posts where the last post you pull out becomes a divider, so the stretches on either side never affect each other. In the DP, the chosen last balloon k is that divider, and dp[l][r] stores the best score for the stretch between two fixed posts l and r.

Flip the question: which balloon bursts last in an interval? Say the open interval is (l, r), meaning the balloons strictly between positions l and r. If k is the last one to burst, every other balloon in the interval is gone before k goes. At that moment k's neighbors are exactly l and r, so the final burst pays A[l] * A[k] * A[r].

Before k goes, the balloons in (l, k) and the balloons in (k, r) are burst without ever touching each other. Balloon k is still standing between them as a wall. Inside (l, k), the outer neighbors are always l and k, so that part is the same kind of problem on a smaller interval. The same holds for (k, r).

That gives the recurrence dp[l][r] = max over k of dp[l][k] + dp[k][r] + A[l] * A[k] * A[r]. Pad the array with a 1 on each side so the boundary rule disappears. The answer is dp[0][n + 1].

Watch the pattern animation

Worked example

Input: nums = [2, 0, 5, 1, 3, 0, 7, 4, 6, 8]
Output: 1008
Explanation: The two zeros are burst first for 0 coins. That leaves [2,5,1,3,7,4,6,8]. The best order then bursts 1, 3, 4, 6, 7, 5, 2, 8 and earns 15 + 105 + 168 + 336 + 280 + 80 + 16 + 8 = 1008.

Approach 1: Brute force over every burst order

Try every balloon as the next one to burst, collect its coins, remove it, and recurse on what is left. Take the best total. This is the problem statement turned into code, so its correctness is easy to see.

It explores every permutation of the balloons, which is the whole cost.

Steps

  1. If no balloons remain, return 0.
  2. For each position i, read the left neighbor (or 1 if i is first) and the right neighbor (or 1 if i is last).
  3. Remove balloon i from the list and remember its value.
  4. Recurse on the shorter list and add left * value * right to the result.
  5. Put balloon i back so the next choice sees the original list.
  6. Return the largest total over all choices of i.

Dry run

Take the example [2,0,5,1,3,0,7,4,6,8]. The first level tries all 10 balloons, and the immediate coins are:

Burst firstCoins now
2 (index 0)120 = 0
0 (index 1)0
5 (index 2)051 = 0
1 (index 3)513 = 15
3 (index 4)130 = 0
0 (index 5)0
7 (index 6)074 = 0
4 (index 7)746 = 168
6 (index 8)468 = 192
8 (index 9)681 = 48

Each choice then recurses on 9 balloons, then 8, and so on. That is 10 factorial = 3,628,800 complete orders.

The best of them totals 1008, so the function returns 1008. The biggest first payoff (192) does not matter by itself. Only the full sequence total counts.

Complexity

TimeO(n * n!)
SpaceO(n)

Here n is the number of balloons. The first choice has n options, the next n - 1, and so on, so the recursion tree has about e * n factorial nodes. Each node scans its list in O(n) work when computing neighbors and shifting elements.

The list is edited in place, so memory is the recursion depth, O(n). For n = 300 this never finishes.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxCoins(self, nums: List[int]) -> int:
        def go() -> int:
            if not nums:
                return 0
            best = 0
            for i in range(len(nums)):
                left = nums[i - 1] if i > 0 else 1
                right = nums[i + 1] if i + 1 < len(nums) else 1
                v = nums.pop(i)
                best = max(best, left * v * right + go())
                nums.insert(i, v)  # backtrack
            return best

        return go()

Approach 2: Top-down memoized recursion on the last balloon

What's slow: the brute force treats two different orders that leave the same balloons in the same arrangement as separate work. It also rebuilds the same sub-situations millions of times. Worse, the state after a burst is an arbitrary subset, so there is nothing small to cache.

The insight that fixes it: choose the last balloon in an interval instead of the first. Then the state is only two positions, (l, r), and the answer for that interval never changes. Cache it the first time you compute it.

Steps

  1. Pad the array with a 1 on each side to get A of length n + 2.
  2. Define f(l, r) as the best coins from bursting everything strictly between l and r.
  3. If r - l < 2, no balloons lie between them, so return 0.
  4. For every k from l + 1 to r - 1, treat k as the last burst and compute f(l, k) + f(k, r) + A[l] * A[k] * A[r].
  5. Store the maximum in a table keyed by (l, r) and return it.
  6. Return f(0, n + 1).

Dry run

On the example, the padded array is A = [1,2,0,5,1,3,0,7,4,6,8,1], so l = 0 and r = 11 at the top. There are 12 positions, so the table has 66 pairs, and 55 of them contain at least one balloon.

The top call tries k = 1 through k = 10. For k = 10 (the balloon valued 8) it needs f(0, 10), which is 1000, and f(10, 11), which is 0. The last burst pays 1 * 8 * 1 = 8, so this branch gives 1008.

Every other k gives at most 1002 (for example k = 1, the balloon valued 2, gives 1000 + 2). The maximum is 1008. Each of the 55 sub-intervals is computed once and then read from the table.

Complexity

TimeO(n^3)
SpaceO(n^2)

Let n be the number of balloons. There are about (n + 2)^2 / 2 distinct pairs (l, r), and each is computed once. One computation loops over at most n values of k and does O(1) work for each, so the total is O(n^3). The memo table holds O(n^2) ints, and the recursion is at most n + 1 levels deep.

PythonTested in our runner

from typing import List, Optional
from functools import lru_cache

class Solution:
    def maxCoins(self, nums: List[int]) -> int:
        A = [1] + nums + [1]

        @lru_cache(maxsize=None)
        def f(l: int, r: int) -> int:
            best = 0
            for k in range(l + 1, r):  # k is the last balloon burst in (l, r)
                best = max(best, f(l, k) + A[l] * A[k] * A[r] + f(k, r))
            return best

        return f(0, len(A) - 1)
Interval DP pattern infographic for Burst Balloons

Solution pattern

Interval DP

Part of Dynamic Programming (DP) Patterns

Approach 3: Bottom-up interval DPOptimalInterval DP

What's slow: the memoized version is already O(n^3), but it pays for recursion and, in some languages, for call depth. It also computes intervals in an order the call stack decides.

The insight that fixes it: dp[l][r] only reads intervals that are strictly shorter. So fill the table by interval length, from one balloon up to all of them. Every cell you read is already final.

As a bonus, you can drop zeros first. A zero balloon pays nothing when burst, and removing it early only makes the remaining neighbors adjacent sooner, which never lowers a payout. So burst all zeros first for free and skip them.

Steps

  1. Build A as [1] plus every positive value of nums plus [1]. Let m be its length.
  2. Create an m x m table dp filled with 0. Entry dp[l][r] is the best for balloons strictly between l and r.
  3. Loop span = r - l from 2 up to m - 1. A span of 2 means exactly one balloon in between.
  4. For each l with l + span < m, set r = l + span.
  5. For each k in l + 1 .. r - 1, compute dp[l][k] + A[l] * A[k] * A[r] + dp[k][r].
  6. Store the best value in dp[l][r].
  7. Return dp[0][m - 1].

Dry run

Drop the two zeros from the example. The padded array is A = [1,2,5,1,3,7,4,6,8,1], so m = 10. The table below shows the cells on the path to the answer. Each winner k is a position in A.

SpanCell (l, r)Winning k (value)Computationdp value
2(2, 4)3 (1)0 + 513 + 015
2(5, 7)6 (4)0 + 746 + 0168
3(2, 5)4 (3)15 + 537 + 0120
3(5, 8)7 (6)168 + 768 + 0504
6(2, 8)5 (7)120 + 578 + 504904
7(1, 8)2 (5)0 + 258 + 904984
8(0, 8)1 (2)0 + 128 + 9841000
9(0, 9)8 (8)1000 + 181 + 01008

Smaller spans fill every other cell first. For instance dp[0][2] = 10 and dp[7][9] = 48. At the top, k = 1 through k = 7 give 1002, 959, 720, 750, 771, 536 and 624, all below 1000 + 8.

Reading the winners from the outside in gives the burst order in reverse: 8 last, 2 before it, then 5, then 7. Played forward, the bursts are 1, 3, 4, 6, 7, 5, 2, 8 with 15, 105, 168, 336, 280, 80, 16, 8 coins, which add to 1008.

Complexity

TimeO(n^3)
SpaceO(n^2)

Let n be the number of balloons. The loops choose a left end, a right end and a last balloon strictly between them, so the work equals the number of triples l < k < r over n + 2 positions. That is C(n + 2, 3), about n^3 / 6, and each triple costs O(1). For n = 300 it is about 4.5 million steps.

The table has (n + 2)^2 cells, so space is O(n^2).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxCoins(self, nums: List[int]) -> int:
        # Zero balloons are burst first for 0 coins, so drop them.
        A = [1] + [x for x in nums if x > 0] + [1]
        m = len(A)
        # dp[l][r] = best coins from bursting everything strictly between l and r
        dp = [[0] * m for _ in range(m)]
        for span in range(2, m):
            for l in range(m - span):
                r = l + span
                best = 0
                for k in range(l + 1, r):  # k is the last balloon burst in (l, r)
                    c = dp[l][k] + A[l] * A[k] * A[r] + dp[k][r]
                    if c > best:
                        best = c
                dp[l][r] = best
        return dp[0][m - 1]

Common mistakes

  • Scoring the last burst as A[k - 1] * A[k] * A[k + 1]. When k is last in (l, r) its neighbors are l and r, so the coins are A[l] * A[k] * A[r].
  • Skipping the padding and special-casing the edges in the transition. Build A = [1] + nums + [1] once and let every interval use plain indices.
  • Filling the table by left first and right second in increasing order. Then dp[k][right] for k > left is not ready yet. Loop by interval length so shorter intervals are always done.
  • Defining the state by the first balloon burst, as in dp[l][r] = ... burst k first. The two halves then become adjacent and share boundary values. Define it by the last balloon.
  • Letting k run over range(left, right + 1). The endpoints are the fixed neighbors, not balloons in the interval. Use range(left + 1, right).
  • Choosing greedily, such as always bursting the smallest balloon or the one with the biggest payoff now. Neither is correct, because a small balloon can sit between two large ones that you want next to each other later. Use the DP.

Edge cases

  • nums = [7]: a single balloon pays 1 * 7 * 1 = 7.
  • nums = [1, 5]: the answer is 10. Burst 1 first for 1 * 1 * 5 = 5, then 5 for 1 * 5 * 1 = 5.
  • nums = [0] or all zeros: every burst pays 0, so the answer is 0. With zeros stripped, A = [1, 1] and dp[0][1] = 0.
  • A zero between two large values, like [9, 0, 9]: burst the zero first for free, then 9 pays 1 * 9 * 9 = 81 and the last 9 pays 9. The answer is 90.
  • All balloons equal to 100 with n = 300: the total is near 3 * 10^8, which still fits in a 32-bit int.
  • Strictly increasing or decreasing arrays: no shortcut applies, and the DP must still try every last balloon in each interval.

Follow-ups interviewers ask

How do you print the actual burst order, not only the total?
Store the winning k for each cell in a second table, choice[l][r]. Then rebuild recursively: to order the interval (l, r), order (l, choice), then order (choice, r), then append choice as the last burst. This costs O(n^2) extra space and O(n) time to rebuild.
Can you beat O(n^3) time?
I do not know of a simpler general method that does. Each of the O(n^2) intervals genuinely needs a maximum over its possible last balloons, and I can only claim O(n^3) as proven. The memory can stay O(n^2), because a cell may depend on any shorter interval that shares an endpoint.
What changes if values can be negative?
The DP itself still works, because it never assumes values are non-negative. The zero-stripping shortcut breaks, though. With negative values, removing a balloon early can change payouts in either direction, so you must keep every balloon and run the full table.

Burst Balloons FAQ

What is the time complexity of Burst Balloons?

O(n^3) for the interval DP, where n is the number of balloons. There are about n^3 / 6 triples of left end, last balloon and right end, and each costs O(1). The table adds O(n^2) space. The brute force over burst orders is O(n * n factorial).

Why use interval DP for Burst Balloons?

The best score for a stretch of balloons depends only on the best scores of smaller stretches, once you decide which balloon bursts last. That makes the subproblems independent and cacheable by their two endpoints. Interval DP is the pattern that fills such a table in order of interval length.

Why think about the last balloon instead of the first?

Bursting a balloon first makes its neighbors adjacent, so the left and right parts interact. Bursting it last keeps it as a fixed wall between them, and its neighbors at that moment are the interval's two boundaries. The two sides are then separate problems.

Why does the Burst Balloons solution pad the array with 1s?

The statement treats a missing neighbor as a balloon valued 1. Adding real 1s at both ends makes the formula A[l] * A[k] * A[r] valid for every interval without special cases. The answer is then the entry for the whole padded range.

Can Burst Balloons be solved in O(1) extra space?

No known method does. Each interval needs the saved results of shorter intervals that share an endpoint, so the O(n^2) table cannot be shrunk to a few variables. Recursion alone does not avoid this: without caching it is exponential.

Do I need a greedy approach for LeetCode 312?

No, and greedy fails. Always bursting the smallest balloon or the best immediate payoff ignores that bursting changes who is adjacent to whom. Only the DP over last-burst choices examines every arrangement efficiently.

Asked at

See which companies ask this — Pro

Practise it