15% off all plans & roadmaps Use code
See plansBurst Balloons
- LeetCode 312
- Hard
- Dynamic Programming (DP) Patterns
- Interval DP
Updated
TL;DR: Burst every balloon to maximize coins, where each burst pays the product of the balloon and its current neighbors. Choose which balloon bursts last in each interval, which makes the subproblems independent and gives an O(n^3) interval DP.
Problem
You are given n balloons indexed from 0 to n - 1. Each balloon has a number painted on it, given by the array nums. You must burst every balloon.
Bursting balloon i earns nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 falls outside the array, treat that neighbor as a balloon painted with 1. After a balloon bursts, it is removed and its neighbors become adjacent.
Return the maximum number of coins you can collect by choosing the order of bursts well.
Example 1
Input: nums = [3,1,5,8] Output: 167 Explanation: [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [], and the coins are 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167.
Example 2
Input: nums = [1,5] Output: 10
Constraints
n == nums.length1 <= n <= 3000 <= nums[i] <= 100
Constraints that matter
- n up to 300 rules out trying every burst order. 300 factorial is far beyond any limit, and even 2^300 subsets are impossible.
- n up to 300 allows O(n^3). That is about 4.5 million (left, last, right) triples, which runs in well under a second.
- A 2D table of about 302 x 302 ints is tiny, so O(n^2) memory is no concern.
- Values up to 100 give at most 100^3 = 10^6 coins per burst. The total stays near 3 * 10^8 at most, so a 32-bit int holds it.
- Values can be 0, so a burst can pay nothing. Zeros are harmless to the DP and can be removed up front as a shortcut.
Hints
Hint 1
This is interval DP.
Hint 2
Try every balloon as the next one to burst, collect its coins, remove it, and recurse on what is left.
Solution
Intuition
This is interval DP. The natural question is which balloon to burst first, but that choice breaks the problem. When you burst balloon k first, its two neighbors become adjacent. The left part and the right part now depend on each other, so you cannot solve them separately.
Picture a row of fence posts where the last post you pull out becomes a divider, so the stretches on either side never affect each other. In the DP, the chosen last balloon k is that divider, and dp[l][r] stores the best score for the stretch between two fixed posts l and r.
Flip the question: which balloon bursts last in an interval? Say the open interval is (l, r), meaning the balloons strictly between positions l and r. If k is the last one to burst, every other balloon in the interval is gone before k goes. At that moment k's neighbors are exactly l and r, so the final burst pays A[l] * A[k] * A[r].
Before k goes, the balloons in (l, k) and the balloons in (k, r) are burst without ever touching each other. Balloon k is still standing between them as a wall. Inside (l, k), the outer neighbors are always l and k, so that part is the same kind of problem on a smaller interval. The same holds for (k, r).
That gives the recurrence dp[l][r] = max over k of dp[l][k] + dp[k][r] + A[l] * A[k] * A[r]. Pad the array with a 1 on each side so the boundary rule disappears. The answer is dp[0][n + 1].
Worked example
Input: nums = [2, 0, 5, 1, 3, 0, 7, 4, 6, 8] Output: 1008 Explanation: The two zeros are burst first for 0 coins. That leaves [2,5,1,3,7,4,6,8]. The best order then bursts 1, 3, 4, 6, 7, 5, 2, 8 and earns 15 + 105 + 168 + 336 + 280 + 80 + 16 + 8 = 1008.
Approach 1: Brute force over every burst order
Try every balloon as the next one to burst, collect its coins, remove it, and recurse on what is left. Take the best total. This is the problem statement turned into code, so its correctness is easy to see.
It explores every permutation of the balloons, which is the whole cost.
Steps
- If no balloons remain, return 0.
- For each position
i, read the left neighbor (or 1 ifiis first) and the right neighbor (or 1 ifiis last). - Remove balloon
ifrom the list and remember its value. - Recurse on the shorter list and add
left * value * rightto the result. - Put balloon
iback so the next choice sees the original list. - Return the largest total over all choices of
i.
Dry run
Take the example [2,0,5,1,3,0,7,4,6,8]. The first level tries all 10 balloons, and the immediate coins are:
| Burst first | Coins now |
|---|---|
| 2 (index 0) | 120 = 0 |
| 0 (index 1) | 0 |
| 5 (index 2) | 051 = 0 |
| 1 (index 3) | 513 = 15 |
| 3 (index 4) | 130 = 0 |
| 0 (index 5) | 0 |
| 7 (index 6) | 074 = 0 |
| 4 (index 7) | 746 = 168 |
| 6 (index 8) | 468 = 192 |
| 8 (index 9) | 681 = 48 |
Each choice then recurses on 9 balloons, then 8, and so on. That is 10 factorial = 3,628,800 complete orders.
The best of them totals 1008, so the function returns 1008. The biggest first payoff (192) does not matter by itself. Only the full sequence total counts.
Complexity
| Time | O(n * n!) |
|---|---|
| Space | O(n) |
Here n is the number of balloons. The first choice has n options, the next n - 1, and so on, so the recursion tree has about e * n factorial nodes. Each node scans its list in O(n) work when computing neighbors and shifting elements.
The list is edited in place, so memory is the recursion depth, O(n). For n = 300 this never finishes.
PythonTested in our runner
from typing import List, Optional
class Solution:
def maxCoins(self, nums: List[int]) -> int:
def go() -> int:
if not nums:
return 0
best = 0
for i in range(len(nums)):
left = nums[i - 1] if i > 0 else 1
right = nums[i + 1] if i + 1 < len(nums) else 1
v = nums.pop(i)
best = max(best, left * v * right + go())
nums.insert(i, v) # backtrack
return best
return go()
JavaTested in our runner
import java.util.*;
class Solution {
public int maxCoins(int[] nums) {
List<Integer> arr = new ArrayList<>();
for (int x : nums) arr.add(x);
return go(arr);
}
private int go(List<Integer> arr) {
if (arr.isEmpty()) return 0;
int best = 0;
for (int i = 0; i < arr.size(); i++) {
int left = i > 0 ? arr.get(i - 1) : 1;
int right = i + 1 < arr.size() ? arr.get(i + 1) : 1;
int v = arr.get(i);
arr.remove(i);
best = Math.max(best, left * v * right + go(arr));
arr.add(i, v); // backtrack
}
return best;
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxCoins(vector<int>& nums) {
return go(nums);
}
private:
int go(vector<int>& arr) {
if (arr.empty()) return 0;
int best = 0;
for (int i = 0; i < (int)arr.size(); i++) {
int left = i > 0 ? arr[i - 1] : 1;
int right = i + 1 < (int)arr.size() ? arr[i + 1] : 1;
int v = arr[i];
arr.erase(arr.begin() + i);
best = max(best, left * v * right + go(arr));
arr.insert(arr.begin() + i, v); // backtrack
}
return best;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var maxCoins = function(nums) {
const go = () => {
if (nums.length === 0) return 0;
let best = 0;
for (let i = 0; i < nums.length; i++) {
const left = i > 0 ? nums[i - 1] : 1;
const right = i + 1 < nums.length ? nums[i + 1] : 1;
const v = nums[i];
nums.splice(i, 1);
best = Math.max(best, left * v * right + go());
nums.splice(i, 0, v); // backtrack
}
return best;
};
return go();
};
GoTested in our runner
func maxCoins(nums []int) int {
var solve func(arr []int) int
solve = func(arr []int) int {
n := len(arr)
if n == 0 {
return 0
}
best := 0
for i := 0; i < n; i++ {
l, r := 1, 1
if i > 0 {
l = arr[i-1]
}
if i+1 < n {
r = arr[i+1]
}
v := arr[i]
copy(arr[i:], arr[i+1:]) // remove i by shifting left
c := l*v*r + solve(arr[:n-1])
copy(arr[i+1:], arr[i:n-1]) // shift back
arr[i] = v
if c > best {
best = c
}
}
return best
}
return solve(nums)
}
C#Tested in our runner
public class Solution {
public int maxCoins(int[] nums) {
var arr = new List<int>(nums);
return Go(arr);
}
private int Go(List<int> arr) {
if (arr.Count == 0) return 0;
int best = 0;
for (int i = 0; i < arr.Count; i++) {
int left = i > 0 ? arr[i - 1] : 1;
int right = i + 1 < arr.Count ? arr[i + 1] : 1;
int v = arr[i];
arr.RemoveAt(i);
best = Math.Max(best, left * v * right + Go(arr));
arr.Insert(i, v); // backtrack
}
return best;
}
}
Approach 2: Top-down memoized recursion on the last balloon
What's slow: the brute force treats two different orders that leave the same balloons in the same arrangement as separate work. It also rebuilds the same sub-situations millions of times. Worse, the state after a burst is an arbitrary subset, so there is nothing small to cache.
The insight that fixes it: choose the last balloon in an interval instead of the first. Then the state is only two positions, (l, r), and the answer for that interval never changes. Cache it the first time you compute it.
Steps
- Pad the array with a 1 on each side to get
Aof length n + 2. - Define
f(l, r)as the best coins from bursting everything strictly betweenlandr. - If
r - l < 2, no balloons lie between them, so return 0. - For every
kfroml + 1tor - 1, treatkas the last burst and computef(l, k) + f(k, r) + A[l] * A[k] * A[r]. - Store the maximum in a table keyed by
(l, r)and return it. - Return
f(0, n + 1).
Dry run
On the example, the padded array is A = [1,2,0,5,1,3,0,7,4,6,8,1], so l = 0 and r = 11 at the top. There are 12 positions, so the table has 66 pairs, and 55 of them contain at least one balloon.
The top call tries k = 1 through k = 10. For k = 10 (the balloon valued 8) it needs f(0, 10), which is 1000, and f(10, 11), which is 0. The last burst pays 1 * 8 * 1 = 8, so this branch gives 1008.
Every other k gives at most 1002 (for example k = 1, the balloon valued 2, gives 1000 + 2). The maximum is 1008. Each of the 55 sub-intervals is computed once and then read from the table.
Complexity
| Time | O(n^3) |
|---|---|
| Space | O(n^2) |
Let n be the number of balloons. There are about (n + 2)^2 / 2 distinct pairs (l, r), and each is computed once. One computation loops over at most n values of k and does O(1) work for each, so the total is O(n^3). The memo table holds O(n^2) ints, and the recursion is at most n + 1 levels deep.
PythonTested in our runner
from typing import List, Optional
from functools import lru_cache
class Solution:
def maxCoins(self, nums: List[int]) -> int:
A = [1] + nums + [1]
@lru_cache(maxsize=None)
def f(l: int, r: int) -> int:
best = 0
for k in range(l + 1, r): # k is the last balloon burst in (l, r)
best = max(best, f(l, k) + A[l] * A[k] * A[r] + f(k, r))
return best
return f(0, len(A) - 1)
JavaTested in our runner
import java.util.*;
class Solution {
private int[] A;
private int[][] memo;
public int maxCoins(int[] nums) {
int n = nums.length;
A = new int[n + 2];
A[0] = 1;
A[n + 1] = 1;
for (int i = 0; i < n; i++) A[i + 1] = nums[i];
memo = new int[n + 2][n + 2];
for (int[] row : memo) Arrays.fill(row, -1);
return solve(0, n + 1);
}
private int solve(int l, int r) {
if (r - l < 2) return 0;
if (memo[l][r] >= 0) return memo[l][r];
int best = 0;
for (int k = l + 1; k < r; k++) {
best = Math.max(best, solve(l, k) + A[l] * A[k] * A[r] + solve(k, r));
}
memo[l][r] = best;
return best;
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxCoins(vector<int>& nums) {
int n = nums.size();
A.assign(n + 2, 1);
for (int i = 0; i < n; i++) A[i + 1] = nums[i];
memo.assign(n + 2, vector<int>(n + 2, -1));
return solve(0, n + 1);
}
private:
vector<int> A;
vector<vector<int>> memo;
int solve(int l, int r) {
if (r - l < 2) return 0;
if (memo[l][r] >= 0) return memo[l][r];
int best = 0;
for (int k = l + 1; k < r; k++) {
best = max(best, solve(l, k) + A[l] * A[k] * A[r] + solve(k, r));
}
return memo[l][r] = best;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var maxCoins = function(nums) {
const A = [1, ...nums, 1];
const m = A.length;
const memo = Array.from({ length: m }, () => new Array(m).fill(-1));
const solve = (l, r) => {
if (r - l < 2) return 0;
if (memo[l][r] >= 0) return memo[l][r];
let best = 0;
for (let k = l + 1; k < r; k++) {
best = Math.max(best, solve(l, k) + A[l] * A[k] * A[r] + solve(k, r));
}
memo[l][r] = best;
return best;
};
return solve(0, m - 1);
};
GoTested in our runner
func maxCoins(nums []int) int {
A := make([]int, 0, len(nums)+2)
A = append(A, 1)
A = append(A, nums...)
A = append(A, 1)
m := len(A)
memo := make([][]int, m)
for i := range memo {
memo[i] = make([]int, m)
for j := range memo[i] {
memo[i][j] = -1
}
}
var solve func(l, r int) int
solve = func(l, r int) int {
if r-l < 2 {
return 0
}
if memo[l][r] >= 0 {
return memo[l][r]
}
best := 0
for k := l + 1; k < r; k++ {
c := solve(l, k) + A[l]*A[k]*A[r] + solve(k, r)
if c > best {
best = c
}
}
memo[l][r] = best
return best
}
return solve(0, m-1)
}
C#Tested in our runner
public class Solution {
private int[] A;
private int[,] memo;
public int maxCoins(int[] nums) {
int n = nums.Length;
A = new int[n + 2];
A[0] = 1;
A[n + 1] = 1;
for (int i = 0; i < n; i++) A[i + 1] = nums[i];
memo = new int[n + 2, n + 2];
for (int i = 0; i < n + 2; i++)
for (int j = 0; j < n + 2; j++)
memo[i, j] = -1;
return Solve(0, n + 1);
}
private int Solve(int l, int r) {
if (r - l < 2) return 0;
if (memo[l, r] >= 0) return memo[l, r];
int best = 0;
for (int k = l + 1; k < r; k++) {
best = Math.Max(best, Solve(l, k) + A[l] * A[k] * A[r] + Solve(k, r));
}
memo[l, r] = best;
return best;
}
}

Solution pattern
Interval DP
Approach 3: Bottom-up interval DPOptimalInterval DP
What's slow: the memoized version is already O(n^3), but it pays for recursion and, in some languages, for call depth. It also computes intervals in an order the call stack decides.
The insight that fixes it: dp[l][r] only reads intervals that are strictly shorter. So fill the table by interval length, from one balloon up to all of them. Every cell you read is already final.
As a bonus, you can drop zeros first. A zero balloon pays nothing when burst, and removing it early only makes the remaining neighbors adjacent sooner, which never lowers a payout. So burst all zeros first for free and skip them.
Steps
- Build
Aas[1]plus every positive value ofnumsplus[1]. Letmbe its length. - Create an
m x mtabledpfilled with 0. Entrydp[l][r]is the best for balloons strictly betweenlandr. - Loop
span = r - lfrom 2 up tom - 1. A span of 2 means exactly one balloon in between. - For each
lwithl + span < m, setr = l + span. - For each
kinl + 1 .. r - 1, computedp[l][k] + A[l] * A[k] * A[r] + dp[k][r]. - Store the best value in
dp[l][r]. - Return
dp[0][m - 1].
Dry run
Drop the two zeros from the example. The padded array is A = [1,2,5,1,3,7,4,6,8,1], so m = 10. The table below shows the cells on the path to the answer. Each winner k is a position in A.
| Span | Cell (l, r) | Winning k (value) | Computation | dp value |
|---|---|---|---|---|
| 2 | (2, 4) | 3 (1) | 0 + 513 + 0 | 15 |
| 2 | (5, 7) | 6 (4) | 0 + 746 + 0 | 168 |
| 3 | (2, 5) | 4 (3) | 15 + 537 + 0 | 120 |
| 3 | (5, 8) | 7 (6) | 168 + 768 + 0 | 504 |
| 6 | (2, 8) | 5 (7) | 120 + 578 + 504 | 904 |
| 7 | (1, 8) | 2 (5) | 0 + 258 + 904 | 984 |
| 8 | (0, 8) | 1 (2) | 0 + 128 + 984 | 1000 |
| 9 | (0, 9) | 8 (8) | 1000 + 181 + 0 | 1008 |
Smaller spans fill every other cell first. For instance dp[0][2] = 10 and dp[7][9] = 48. At the top, k = 1 through k = 7 give 1002, 959, 720, 750, 771, 536 and 624, all below 1000 + 8.
Reading the winners from the outside in gives the burst order in reverse: 8 last, 2 before it, then 5, then 7. Played forward, the bursts are 1, 3, 4, 6, 7, 5, 2, 8 with 15, 105, 168, 336, 280, 80, 16, 8 coins, which add to 1008.
Complexity
| Time | O(n^3) |
|---|---|
| Space | O(n^2) |
Let n be the number of balloons. The loops choose a left end, a right end and a last balloon strictly between them, so the work equals the number of triples l < k < r over n + 2 positions. That is C(n + 2, 3), about n^3 / 6, and each triple costs O(1). For n = 300 it is about 4.5 million steps.
The table has (n + 2)^2 cells, so space is O(n^2).
PythonTested in our runner
from typing import List, Optional
class Solution:
def maxCoins(self, nums: List[int]) -> int:
# Zero balloons are burst first for 0 coins, so drop them.
A = [1] + [x for x in nums if x > 0] + [1]
m = len(A)
# dp[l][r] = best coins from bursting everything strictly between l and r
dp = [[0] * m for _ in range(m)]
for span in range(2, m):
for l in range(m - span):
r = l + span
best = 0
for k in range(l + 1, r): # k is the last balloon burst in (l, r)
c = dp[l][k] + A[l] * A[k] * A[r] + dp[k][r]
if c > best:
best = c
dp[l][r] = best
return dp[0][m - 1]
JavaTested in our runner
import java.util.*;
class Solution {
public int maxCoins(int[] nums) {
int cnt = 0;
for (int x : nums) if (x > 0) cnt++;
int m = cnt + 2;
int[] A = new int[m];
A[0] = 1;
A[m - 1] = 1;
int p = 1;
for (int x : nums) if (x > 0) A[p++] = x; // zeros are burst first for free
int[][] dp = new int[m][m];
for (int span = 2; span < m; span++) {
for (int l = 0; l + span < m; l++) {
int r = l + span;
int best = 0;
for (int k = l + 1; k < r; k++) { // k is the last burst in (l, r)
int c = dp[l][k] + A[l] * A[k] * A[r] + dp[k][r];
if (c > best) best = c;
}
dp[l][r] = best;
}
}
return dp[0][m - 1];
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxCoins(vector<int>& nums) {
vector<int> A;
A.push_back(1);
for (int x : nums) if (x > 0) A.push_back(x); // zeros are burst first for free
A.push_back(1);
int m = A.size();
vector<vector<int>> dp(m, vector<int>(m, 0));
for (int span = 2; span < m; span++) {
for (int l = 0; l + span < m; l++) {
int r = l + span;
int best = 0;
for (int k = l + 1; k < r; k++) { // k is the last burst in (l, r)
best = max(best, dp[l][k] + A[l] * A[k] * A[r] + dp[k][r]);
}
dp[l][r] = best;
}
}
return dp[0][m - 1];
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var maxCoins = function(nums) {
// Zero balloons are burst first for 0 coins, so drop them.
const A = [1, ...nums.filter(x => x > 0), 1];
const m = A.length;
const dp = Array.from({ length: m }, () => new Array(m).fill(0));
for (let span = 2; span < m; span++) {
for (let l = 0; l + span < m; l++) {
const r = l + span;
let best = 0;
for (let k = l + 1; k < r; k++) { // k is the last burst in (l, r)
const c = dp[l][k] + A[l] * A[k] * A[r] + dp[k][r];
if (c > best) best = c;
}
dp[l][r] = best;
}
}
return dp[0][m - 1];
};
GoTested in our runner
func maxCoins(nums []int) int {
A := []int{1}
for _, x := range nums {
if x > 0 { // zeros are burst first for free
A = append(A, x)
}
}
A = append(A, 1)
m := len(A)
dp := make([][]int, m)
for i := range dp {
dp[i] = make([]int, m)
}
for span := 2; span < m; span++ {
for l := 0; l+span < m; l++ {
r := l + span
best := 0
for k := l + 1; k < r; k++ { // k is the last burst in (l, r)
c := dp[l][k] + A[l]*A[k]*A[r] + dp[k][r]
if c > best {
best = c
}
}
dp[l][r] = best
}
}
return dp[0][m-1]
}
C#Tested in our runner
public class Solution {
public int maxCoins(int[] nums) {
var A = new List<int> { 1 };
foreach (int x in nums) {
if (x > 0) A.Add(x); // zeros are burst first for free
}
A.Add(1);
int m = A.Count;
int[,] dp = new int[m, m];
for (int span = 2; span < m; span++) {
for (int l = 0; l + span < m; l++) {
int r = l + span;
int best = 0;
for (int k = l + 1; k < r; k++) { // k is the last burst in (l, r)
int c = dp[l, k] + A[l] * A[k] * A[r] + dp[k, r];
if (c > best) best = c;
}
dp[l, r] = best;
}
}
return dp[0, m - 1];
}
}
Common mistakes
- Scoring the last burst as
A[k - 1] * A[k] * A[k + 1]. Whenkis last in(l, r)its neighbors arelandr, so the coins areA[l] * A[k] * A[r]. - Skipping the padding and special-casing the edges in the transition. Build
A = [1] + nums + [1]once and let every interval use plain indices. - Filling the table by
leftfirst andrightsecond in increasing order. Thendp[k][right]fork > leftis not ready yet. Loop by interval length so shorter intervals are always done. - Defining the state by the first balloon burst, as in
dp[l][r] = ... burst k first. The two halves then become adjacent and share boundary values. Define it by the last balloon. - Letting
krun overrange(left, right + 1). The endpoints are the fixed neighbors, not balloons in the interval. Userange(left + 1, right). - Choosing greedily, such as always bursting the smallest balloon or the one with the biggest payoff now. Neither is correct, because a small balloon can sit between two large ones that you want next to each other later. Use the DP.
Edge cases
nums = [7]: a single balloon pays1 * 7 * 1 = 7.nums = [1, 5]: the answer is 10. Burst 1 first for 1 * 1 * 5 = 5, then 5 for 1 * 5 * 1 = 5.nums = [0]or all zeros: every burst pays 0, so the answer is 0. With zeros stripped,A = [1, 1]anddp[0][1] = 0.- A zero between two large values, like
[9, 0, 9]: burst the zero first for free, then 9 pays 1 * 9 * 9 = 81 and the last 9 pays 9. The answer is 90. - All balloons equal to 100 with n = 300: the total is near 3 * 10^8, which still fits in a 32-bit int.
- Strictly increasing or decreasing arrays: no shortcut applies, and the DP must still try every last balloon in each interval.
Follow-ups interviewers ask
- How do you print the actual burst order, not only the total?
- Store the winning
kfor each cell in a second table,choice[l][r]. Then rebuild recursively: to order the interval(l, r), order(l, choice), then order(choice, r), then appendchoiceas the last burst. This costs O(n^2) extra space and O(n) time to rebuild. - Can you beat O(n^3) time?
- I do not know of a simpler general method that does. Each of the O(n^2) intervals genuinely needs a maximum over its possible last balloons, and I can only claim O(n^3) as proven. The memory can stay O(n^2), because a cell may depend on any shorter interval that shares an endpoint.
- What changes if values can be negative?
- The DP itself still works, because it never assumes values are non-negative. The zero-stripping shortcut breaks, though. With negative values, removing a balloon early can change payouts in either direction, so you must keep every balloon and run the full table.
Burst Balloons FAQ
What is the time complexity of Burst Balloons?
O(n^3) for the interval DP, where n is the number of balloons. There are about n^3 / 6 triples of left end, last balloon and right end, and each costs O(1). The table adds O(n^2) space. The brute force over burst orders is O(n * n factorial).
Why use interval DP for Burst Balloons?
The best score for a stretch of balloons depends only on the best scores of smaller stretches, once you decide which balloon bursts last. That makes the subproblems independent and cacheable by their two endpoints. Interval DP is the pattern that fills such a table in order of interval length.
Why think about the last balloon instead of the first?
Bursting a balloon first makes its neighbors adjacent, so the left and right parts interact. Bursting it last keeps it as a fixed wall between them, and its neighbors at that moment are the interval's two boundaries. The two sides are then separate problems.
Why does the Burst Balloons solution pad the array with 1s?
The statement treats a missing neighbor as a balloon valued 1. Adding real 1s at both ends makes the formula A[l] * A[k] * A[r] valid for every interval without special cases. The answer is then the entry for the whole padded range.
Can Burst Balloons be solved in O(1) extra space?
No known method does. Each interval needs the saved results of shorter intervals that share an endpoint, so the O(n^2) table cannot be shrunk to a few variables. Recursion alone does not avoid this: without caching it is exponential.
Do I need a greedy approach for LeetCode 312?
No, and greedy fails. Always bursting the smallest balloon or the best immediate payoff ignores that bursting changes who is adjacent to whom. Only the DP over last-burst choices examines every arrangement efficiently.
Asked at
See which companies ask this — Pro
Related problems
- Remove Boxes · same technique: Interval DP
- Stone Game · same technique: Interval DP
- Stone Game II · same technique: Interval DP
- Distinct Subsequences · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Path in a Matrix · same pattern: Dynamic Programming (DP) Patterns
- Regular Expression Matching · same pattern: Dynamic Programming (DP) Patterns
- Word Break II · same pattern: Dynamic Programming (DP) Patterns
- Stone Game III · same pattern: Dynamic Programming (DP) Patterns
- Best Time to Buy and Sell Stock III · same pattern: Dynamic Programming (DP) Patterns
- Best Time to Buy and Sell Stock IV · same pattern: Dynamic Programming (DP) Patterns