</>

312. Burst Balloons

Hard NeetCode 150
2-D Dynamic Programming Time O(n^3) Space O(n^2)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
2-D Dynamic Programming
Time
O(n^3)
Space
O(n^2)

Standard Solution (C++)

SummaryGiven balloons each holding a number, bursting one earns nums[left] * nums[i] * nums[right] (using virtual 1s at the ends); maximize total coins over all burst orders.

Approach

Key idea: Think about which balloon is burst LAST within an interval. When balloon k is last in the open interval (left, right), its neighbors are the boundaries left and right, splitting the problem into two independent subintervals.

Steps:

  • Pad the array with 1 on both ends.
  • Let dp[left][right] be the best coins from bursting all balloons strictly between left and right.
  • For every interval, try each k as the last burst: dp[left][k] + nums[left]*nums[k]*nums[right] + dp[k][right].
  • Answer is dp[0][n + 1].
class Solution {
public:
    int maxCoins(vector<int>& nums) {
        int n = nums.size();
        vector<int> vals(n + 2);
        vals[0] = vals[n + 1] = 1;
        for (int i = 0; i < n; ++i) vals[i + 1] = nums[i];
        vector<vector<int>> dp(n + 2, vector<int>(n + 2, 0));
        for (int len = 1; len <= n; ++len) {
            for (int left = 1; left + len - 1 <= n; ++left) {
                int right = left + len - 1;
                for (int k = left; k <= right; ++k) {
                    int coins = vals[left - 1] * vals[k] * vals[right + 1];
                    coins += dp[left][k - 1] + dp[k + 1][right];
                    dp[left][right] = max(dp[left][right], coins);
                }
            }
        }
        return dp[1][n];
    }
};
Time O(n^3) Space O(n^2)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern