sagelearnai

Burst Balloons

Difficulty: Hard · Pattern: 2-D Dynamic Programming · LeetCode #312

Bursting balloon i earns nums[i−1] × nums[i] × nums[i+1] coins, using its current neighbors (treat positions outside the array as 1). Then the balloon disappears and its neighbors become adjacent. Return the maximum coins obtainable by bursting all of them.

Examples

text
[3,1,5,8]  →  167    (burst 1, 5, 3, 8: 3·1·5 + 3·5·8 + 1·3·8 + 1·8·1)
[1,5]      →  10

Hints

  1. Choosing the first balloon to burst leaves two halves whose neighbors still depend on each other. That's messy.
  2. Instead choose the last balloon to burst in an open interval (i, j). While it's the last one inside, its neighbors are exactly the boundaries i and j.

Approach

Pad the array: a = [1] + nums + [1]. dp[i][j] = the max coins from bursting all balloons strictly between i and j:

text
dp[i][j] = max over k in (i, j) of  dp[i][k] + a[i]·a[k]·a[j] + dp[k][j]

Since k is the last balloon burst inside (i, j), the subproblems (i, k) and (k, j) are independent, with i, k and j standing as fixed walls. Fill by increasing interval length. That's O(n³) time and O(n²) space.

"Think about the last operation" is the key reframing for many interval DPs (Matrix Chain Multiplication, Minimum Cost to Cut a Stick).

Complexity

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

Python solution
def maxCoins(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
            best = 0
            for k in range(i + 1, j):
                v = dp[i][k] + a[i] * a[k] * a[j] + dp[k][j]
                if v > best:
                    best = v
            dp[i][j] = best
    return dp[0][n - 1]
JavaScript solution
function maxCoins(nums) {
  const a = [1, ...nums, 1], n = a.length;
  const dp = Array.from({ length: n }, () => new Array(n).fill(0));
  for (let len = 2; len < n; len++) for (let i = 0; i + len < n; i++) {
    const j = i + len;
    for (let k = i + 1; k < j; k++) dp[i][j] = Math.max(dp[i][j], dp[i][k] + a[i] * a[k] * a[j] + dp[k][j]);
  }
  return dp[0][n - 1];
}