A row of balloons has a number on each one, given as nums. You burst them one at a time, in any order you like, until none are left.
Bursting a balloon earns its number times the numbers of the balloons directly to its left and right at that moment. Once a balloon is gone, its two neighbours become next to each other. If there is no balloon on a side, count that side as 1. Return the most coins you can earn in total.
Example 1
Input: nums = [2, 4, 3] Output: 33 Why: burst 4 (2×4×3 = 24), then 2 (1×2×3 = 6), then 3 (1×3×1 = 3)
2 more examples and the constraints
Example 2
Input: nums = [5] Output: 5 Why: both sides are empty, so 1 × 5 × 1
Example 3
Input: nums = [0, 7] Output: 7 Why: burst 0 first for 0 coins, then 7 alone for 7
Constraints
- 1 ≤ length of nums ≤ 300
- 0 ≤ nums[i] ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Last balloon, top-down with memoO(n³)
- Interval DP tableO(n³)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 300 balloons | Verdict |
|---|---|---|---|
| Last balloon, top-down with memo | O(n³) | Passes; recursion and memo overhead | |
| Interval DP table | O(n³) | Best; same idea, plain loops |
n = number of balloons. Trying every burst order instead would be n!.
Edge cases to test
- One balloon. [5] gives 1 × 5 × 1 = 5.
- Zero balloons in the row. A 0 earns nothing and zeroes any burst next to it; burst it early. [0, 7] gives 7.
- All zeros. [0, 0, 0] gives 0.
- Largest input. 300 balloons of 100: each burst is at most 1,000,000 coins, so the total stays under 300,000,000 and fits in a 32-bit int.
Common mistakes
- Splitting on the first balloon to burst: its neighbours then touch, so the two sides are not independent.
- Forgetting the padding 1s, so the edge balloons are scored against nothing.
- Filling the table by row instead of by range length, so a cell reads ranges that are not filled yet.
How to talk through it
- 1Clarify. Do the outside edges count as 1? Can a number be 0? How many balloons at most?
- 2Explain why greedy and brute force fail. Bursting the biggest or smallest first is wrong on small cases, and trying every order is n!.
- 3Flip to the last burst. If k goes last between lo and hi, it scores vals[lo] × vals[k] × vals[hi], and the two sides never meet.
- 4Code the table. Pad with 1s, fill dp by growing gap, try every k inside, return dp[0][n + 1].
- 5Test out loud. Run one balloon, a row with a 0, and Example 1 by hand before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?