← DSA
HARD

Burst Balloons

PracticeNeetCode ↗LeetCode ↗

Given n balloons with values nums, bursting balloon i earns nums[left] × nums[i] × nums[right] coins, where left and right are its current neighbors after previous bursts. Return the maximum coins obtainable by bursting every balloon.

Example

Input nums = [3,1,5,8]
Output 167

Key Pointers

Step-by-Step Analysis

  1. Pad nums with a 1 at both ends.
  2. Create a 2D dp table, all zeros, sized to the padded array.
  3. Process ranges by increasing length; for each range (l, r), try every k strictly between them as the last balloon burst in that range.
  4. For that choice, the coins earned are nums[l] × nums[k] × nums[r], plus whatever was already earned bursting everything in (l, k) and (k, r) — take the best k.
  5. The final answer sits at dp[0][n-1] of the padded array.

Complexity

Time: O(n³) — Space: O(n²)

Code

def maxCoins(nums: list[int]) -> int:
    balloons = [1] + nums + [1]
    n = len(balloons)
    dp = [[0] * n for _ in range(n)]

    for length in range(2, n):
        for l in range(n - length):
            r = l + length
            for k in range(l + 1, r):
                dp[l][r] = max(
                    dp[l][r],
                    dp[l][k] + balloons[l] * balloons[k] * balloons[r] + dp[k][r],
                )

    return dp[0][n - 1]

Code Explanation

How the solution above works, piece by piece.

  1. Pad the array with 1 on both ends so every balloon always has two neighbours.
  2. dp[l][r] = the most coins from bursting all balloons strictly between l and r (the ends stay).
  3. Choose k as the last balloon burst in that range. At that moment only l and r are left beside it, so it earns balloons[l] * balloons[k] * balloons[r], and the left and right parts are independent: dp[l][k] + dp[k][r].
  4. Fill by increasing range length so smaller ranges are ready first.
  5. dp[0][n-1] is the answer. O(n³) time, O(n²) space.

Visual Walkthrough

Running it on nums = [3, 1, 5, 8]:

Padded balloons and the optimal bursting orderpadded103112538415burst order1538(the last one burst splits the range)dp[l][r] = best coins from bursting everything strictly between l and rdp[0][5] = 167: 8 is burst LAST, next to the two padding 1s
Thinking about which balloon is burst last in a range makes the two sides independent: its neighbours at that moment are exactly the range ends l and r. The best order found is 1, 5, 3, 8 for 3·1·5 + 3·5·8 + 1·3·8 + 1·8·1 = 167.
burst orderreal balloons

Video Explanation

NeetCode — Burst Balloons, LeetCode 312