Burst Balloons Problem
Description
LeetCode Problem 312.
You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.
If you burst the i^th balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.
Return the maximum coins you can collect by bursting the balloons wisely.
Example 1:
Input: nums = [3,1,5,8]
Output: 167
Explanation:
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
Example 2:
Input: nums = [1,5]
Output: 10
Constraints:
- n == nums.length
- 1 <= n <= 500
- 0 <= nums[i] <= 100
Solution
Approach: Interval DP on the Last Balloon
Trying every bursting order takes O(n!) time. The natural split, "which balloon do I burst first", does not work either: after bursting it, its two neighbors become adjacent, so the left and right parts still depend on each other.
The trick is to ask which balloon is burst last. Pad the array with a 1 on each side, values = [1] + nums + [1], and let best[left][right] be the most coins we can get by bursting every balloon strictly between positions left and right, while left and right themselves are still there.
If last is the final balloon burst in that range, then when it bursts, everything else in the range is gone, so its neighbors are exactly left and right:
best[left][right] = max over left < last < right of best[left][last] + values[left] * values[last] * values[right] + best[last][right]
The two sides are now independent, because last stays as a wall between them until the end.
- Fill the table by increasing distance
gap = right - left, starting at 2 (one balloon inside), so the smaller ranges are ready when we need them. - The answer is
best[0][n + 1]: every real balloon, with the two padded 1s as walls.
For [3,1,5,8], bursting 8 last in the whole range gives 1 * 8 * 1 = 8, plus the best for [3,1,5] between the left wall and 8.
Complexity: O(n3) time and O(n2) space, where n is the length of nums.
class Solution:
def maxCoins(self, nums: List[int]) -> int:
# Pad with the imaginary 1-balloons at both ends.
values = [1] + nums + [1]
size = len(values)
# best[left][right] = most coins from bursting every balloon strictly between left and right.
best = [[0] * size for _ in range(size)]
for gap in range(2, size): # distance between the two walls left and right
for left in range(size - gap):
right = left + gap
# Choose the balloon `last` that is burst last inside (left, right):
# at that moment its neighbors are the walls left and right.
for last in range(left + 1, right):
coins = best[left][last] + values[left] * values[last] * values[right] + best[last][right]
if coins > best[left][right]:
best[left][right] = coins
return best[0][size - 1]
Now write it from memory
Close the write-up and solve it yourself against the tests.