Algo-Sim › Advanced DP

Burst Balloons

Hard · Advanced DP · step through it in Java, Python and C++ on your own input

Interval DP: instead of the first balloon to burst, choose the last one in each interval, so the two sides become independent subproblems.

Problem

Balloon i carries the number nums[i]. Bursting it earns nums[left] · nums[i] · nums[right], where left and right are its current neighbours (a missing neighbour counts as 1), and the neighbours then become adjacent. Return the most coins you can collect by bursting every balloon.

Constraints

Edge cases to test

Follow-up questions

Why choose the last balloon, not the first?
If k bursts last in (i, j), its neighbours at that moment are i and j, so the left and right parts are independent: O(n³).
What other problems use this "last split" idea?
Matrix-chain multiplication, Minimum Cost to Cut a Stick (LC 1547), and optimal BST construction.

Solution

Java

public int maxCoins(int[] nums) {
    int n = nums.length;
    int[] v = new int[n + 2];
    v[0] = v[n + 1] = 1;
    for (int i = 0; i < n; i++) v[i + 1] = nums[i];
    int[][] dp = new int[n + 2][n + 2];
    for (int len = 2; len <= n + 1; len++) {
        for (int l = 0; l + len <= n + 1; l++) {
            int r = l + len;
            for (int k = l + 1; k < r; k++) {
                int coins = dp[l][k] + v[l] * v[k] * v[r] + dp[k][r];
                dp[l][r] = Math.max(dp[l][r], coins);
            }
        }
    }
    return dp[0][n + 1];
}

Python

def max_coins(nums):
    n = len(nums)
    v = [1] + nums + [1]
    dp = [[0] * (n + 2) for _ in range(n + 2)]
    for length in range(2, n + 2):
        for l in range(0, n + 2 - length):
            r = l + length
            for k in range(l + 1, r):
                coins = dp[l][k] + v[l] * v[k] * v[r] + dp[k][r]
                dp[l][r] = max(dp[l][r], coins)
    return dp[0][n + 1]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int maxCoins(vector<int> &nums) {
        int n = int(nums.size());
        vector<int> v = vector<int>(n + 2);
        v[0] = v[n + 1] = 1;
        for (int i = 0; i < n; i++)
            v[i + 1] = nums[i];
        vector<vector<int>> dp = vector<vector<int>>(n + 2, vector<int>(n + 2));
        for (int len = 2; len <= n + 1; len++) {
            for (int l = 0; l + len <= n + 1; l++) {
                int r = l + len;
                for (int k = l + 1; k < r; k++) {
                    int coins = dp[l][k] + v[l] * v[k] * v[r] + dp[k][r];
                    dp[l][r] = std::max(dp[l][r], coins);
                }
            }
        }
        return dp[0][n + 1];
    }
};

More Advanced DP problems