Burst Balloons

Hard

Topics
ArrayDynamic ProgrammingInterval DP

You have n balloons with numbers in nums. Bursting balloon i gives nums[i-1]*nums[i]*nums[i+1] coins (treat out-of-range as 1). Return the maximum coins from bursting all balloons.

Example 1

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

Example 2

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

Constraints

  • 1 <= n <= 300
  • 0 <= nums[i] <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Deciding which balloon to burst first is hard because it changes neighbours. Flip it: consider which balloon is burst last in a range — then its neighbours are the fixed range boundaries, giving clean subproblems.

Approach

  1. Pad the array with 1 on both ends.
  2. dp[i][j] = max coins bursting all balloons strictly between i and j.
  3. For each last-burst k in (i, j): dp[i][j] = max(dp[i][k] + nums[i]*nums[k]*nums[j] + dp[k][j]).

Dry Run

nums = [3, 1, 5, 8], padded to a = [1, 3, 1, 5, 8, 1]
dp[i][j] = best coins from bursting everything strictly between i and j,
with i and j still standing. k is the balloon burst LAST in that range.

width 2, one balloon between:
  dp[0][2] = 1*3*1 = 3        dp[1][3] = 3*1*5 = 15
  dp[2][4] = 1*5*8 = 40       dp[3][5] = 5*8*1 = 40

width 3:
  dp[0][3] = 30     k=1 wins: 0 + 1*3*5 + 15   (k=2 gives only 8)
  dp[1][4] = 135    k=3 wins: 15 + 3*5*8 + 0   (k=2 gives 64)
  dp[2][5] = 48     k=4 wins: 40 + 1*8*1 + 0   (k=3 gives 45)

width 4:
  dp[0][4] = 159    dp[1][5] = 159

width 5:
  dp[0][5] = 167    k=4 wins: 159 + 1*8*1 + 0

answer 167

The k=4 at the end is the insight: 8 is the balloon burst LAST, not first. Ask
"which do I burst first" and the two sides are not independent, because
bursting changes who the neighbours are. Ask "which is burst last" and both
sides are already solved subproblems with i and j as their fixed walls.

Complexity

  • Time — O(n^3): over all O(n^2) ranges, an O(n) choice of the last balloon.
  • Space — O(n^2): the interval DP table.

Common Pitfalls

  • Think "last to burst," not "first," so the boundaries stay fixed.

Full Solution — all languages

class Solution:
    def maxCoins(self, nums):
        a=[1]+nums+[1]; n=len(a)
        dp=[[0]*n for _ in range(n)]
        for length in range(2,n):
            for i in range(n-length):
                j=i+length
                for k in range(i+1,j):
                    dp[i][j]=max(dp[i][j],dp[i][k]+a[i]*a[k]*a[j]+dp[k][j])
        return dp[0][n-1]
SensAI
Beta
Tap the mic to stop voice mode