Burst Balloons
Choose a balloon-bursting order that maximizes the total coins collected.
Open on LeetCode ↗Intuition
Choosing the largest balloon first is unreliable because every burst changes its neighbors. It is difficult to describe the first burst of an interval, but easy to describe the last one: its two boundary balloons are then known and still present. Fixing the last balloon splits the remaining work into independent left and right intervals. Interval dynamic programming tests every possible last balloon and retains the best total.
When removing an item changes who becomes adjacent, reverse the decision and ask which item is removed last. If that last choice separates an interval into independent sides, interval DP is the standard pattern.
Approach
Add permanent boundary balloons
Place value one before and after nums. These sentinels make every original balloon use the same formula, including balloons at the original ends.
Define an open interval subproblem
Let solve(left, right) be the maximum coins from bursting balloons strictly between boundary indices left and right. An empty interval returns zero.
Choose which balloon survives until last
For each middle inside the interval, combine the best left interval, the coins values[left] values[middle] values[right], and the best right interval. Memoize the maximum over all choices.
Solution
Common pitfalls
Modeling the first burst
coins = nums[i - 1] * nums[i] * nums[i + 1]
coins = values[left] * values[middle] * values[right]
Original adjacent indices do not remain adjacent after earlier removals; boundaries are known only for the last burst.
Including boundaries in recursive work
solve(left, middle) + solve(middle, right) + solve(middle, middle)
solve(left, middle) + solve(middle, right)
The middle balloon is handled as the last burst and must not appear in either open subinterval.
Omitting sentinel balloons
values = nums
values = [1] + nums + [1]
Sentinels provide the required outside neighbor value for end balloons.
Edge cases
The padded array has no interior index, so the open interval returns zero.
It is last between the two sentinels and earns its own value.
They participate normally; alternative last choices can avoid relying on their zero product.