Skip to problem
←

Burst Balloons

Hard 0 attempts

You're given n balloons lined up in a row, each labeled with a number in the array nums. Bursting balloon i earns nums[i-1] * nums[i] * nums[i+1] coins, where the two neighbors are whatever balloons currently remain adjacent to it (treat positions just past either end as holding an implicit 1). Burst all the balloons, choosing the order that maximizes total coins collected, and return that maximum.

Function contract

Implement maxCoins(nums), where nums lists balloon values in their initial left-to-right order.

Output: The maximum total coins after bursting every balloon. Missing neighbors contribute 1; neighbors change after each burst.

Example 1

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

Example 2

Input
nums = [1,5]
Output
10
Visual Aid
Neighbors change after each burst
[3, 1, 5, 8] burst 1: +15[3, 5, 8] burst 5: +120[3, 8] burst 3: +24[ 8] burst 8: +8Total: 15 + 120 + 24 + 8 = 167

When 5 bursts, its neighbors are 3 and 8. The implicit boundary value is 1.

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

Interval DP

dp[i][j] is the maximum coins from bursting the balloons strictly between boundaries i and j, while both boundary balloons remain. Choose k as the last balloon to burst in that interval: its neighbors are then exactly i and j. The two smaller intervals are independent.

javascript
function maxCoins(nums) {
  const a = [1, ...nums, 1],
    n = a.length;
  const dp = Array.from({ length: n }, () => 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] + dp[k][j] + a[i] * a[k] * a[j]);
      }
    }
  }
  return dp[0][n - 1];
}

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript