LeetcodeAug 24, 2025

Burst Balloons

Hazrat Ali

Leetcode

If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.

Return the maximum coins you can collect by bursting the balloons wisely.

 

Example 1:

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

Example 2:

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

Solution
/**
 * @param {number[]} nums
 * @return {number}
 */
const maxCoins = nums => {
  if (!nums || nums.length === 0) {
    return 0;
  }

  const n = nums.length;
 
  const dp = Array(n + 2)
    .fill()
    .map(() => Array(n + 2).fill(0));
 
  nums = [1, ...nums, 1];

  for (let len = 1; len <= n; len++) {
    for (let start = 1; start + len - 1 <= n; start++) {
      const end = start + len - 1;
      for (let i = start; i <= end; i++) {
        const val = dp[start][i - 1] + nums[i] * nums[start - 1] * nums[end + 1] + dp[i + 1][end];
        dp[start][end] = Math.max(val, dp[start][end]);
      }
    }
  }

  return dp[1][n];
};



Comments