Burst Balloons

Maximize coins from bursting balloons — interval DP keyed by the LAST balloon burst in each range.

Hard
Time O(n^3) Space O(n^2)
LeetCode
4 min read
dp interval-dp

Problem#

Burst balloon i collects nums[i-1] * nums[i] * nums[i+1] (treat out-of-bounds as 1). Return max total coins.

Examples#

  • [3,1,5,8]167

Constraints#

  • 1 <= n <= 300.

Hints#

Hint 1
Pick the LAST balloon burst in each interval instead of the first — its left/right neighbors are then the interval boundaries.

Approach#

Pad with [1, ...nums, 1]. dp[l][r] = max coins from bursting all balloons strictly between l and r. Recurrence: try each k ∈ (l, r) as the last burst in (l, r). Score = nums[l] * nums[k] * nums[r] + dp[l][k] + dp[k][r].

Solution#

Burst Balloons
class Solution {
public:
int maxCoins(vector<int>& nums) {
nums.insert(nums.begin(), 1);
nums.push_back(1);
int n = nums.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int len = 2; len < n; ++len) {
for (int l = 0; l + len < n; ++l) {
int r = l + len;
for (int k = l + 1; k < r; ++k) {
dp[l][r] = max(dp[l][r], dp[l][k] + dp[k][r] + nums[l] * nums[k] * nums[r]);
}
}
}
return dp[0][n - 1];
}
};

Editorial#

Choosing the first burst doesn’t give clean subproblems (neighbors change unpredictably). Choosing the last burst means the neighbors at burst time are the interval boundaries — known from the DP state. Bottom-up by interval length.

Complexity#

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

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.