Problem overview
The method maxCoins receives a list nums with the numbers on a row of balloons, from left to right. You burst the balloons one at a time, in any order you choose, and the method returns the most coins you can collect. Bursting a balloon pays its number times the numbers of its two neighbours, which are the nearest balloons still in the row. When no balloon is left on one side, that side counts as 1. There are 1 to 300 balloons and each number is from 0 to 100.
For nums = [2, 4, 3] the answer is 33. Burst the 4 first: 2 × 4 × 3 = 24. The row is now [2, 3]. Burst the 2: 1 × 2 × 3 = 6. Burst the 3: 1 × 3 × 1 = 3. The total is 33. For [1, 8, 1] the answer is 24, and bursting the 8 first would give only 10. For [3, 0, 4] the answer is 16.
The statement asks for O(n³) time, where n is the length of nums.
Approach: ask which balloon bursts last
Trying every order is far too slow: ten balloons already have 3,628,800 orders. Thinking about which balloon to burst first doesn't help either, because after it bursts, its two neighbours become adjacent and the two halves of the row start to affect each other.
Look at the problem backwards. In a range of the row, ask which balloon bursts last. Until it bursts, it stands between its left part and its right part, so the two parts never touch each other. Each part is a smaller problem of the same kind, and the answers for the parts don't depend on each other.
To make the edges uniform, add a 1 at each end of the row and call the new list values. The two ends are never burst, so every balloon always has two neighbours. Let best[left][right] be the most coins from bursting every balloon strictly between positions left and right of values, while those two stay. If balloon last in that range bursts last, its neighbours are left and right by then, so it pays values[left] × values[last] × values[right]. Everything on its two sides adds best[left][last] and best[last][right]. Try every possible last and keep the largest total.
A range needs the answers of shorter ranges, so fill the short ranges first. The answer is the range from the first added 1 to the last: best[0][n - 1], where n is now the length of values.
Step by step
- Pad the row.
values = [1] + nums + [1]joins the three lists into one new list. - Store the length.
n = len(values), which is two more than the number of balloons. - Create the table.
besthasnrows ofnzeros. Neighbouring positions have no balloon between them, so 0 is already right for them. - Loop over the gap between the two ends:
for gap in range(2, n). A range needs a gap of at least 2 to hold one balloon. - Loop over the left end:
for left in range(n - gap). The right end,left + gap, must stay belown. - Compute the right end:
right = left + gap. - Try each last balloon:
for last in range(left + 1, right). Some balloon bursts last and we don't know which, so we try them all. - Add up the coins:
best[left][last] + best[last][right]for the two parts, plusvalues[left] * values[last] * values[right]for the final burst. - Keep the best: if
coinsbeatsbest[left][right], store it. - Return
best[0][n - 1].
The solution in Python
class Solution:
def maxCoins(self, nums: List[int]) -> int:
values = [1] + nums + [1]
n = len(values)
best = [[0] * n for _ in range(n)]
for gap in range(2, n):
for left in range(n - gap):
right = left + gap
for last in range(left + 1, right):
coins = best[left][last] + best[last][right] + values[left] * values[last] * values[right]
if coins > best[left][right]:
best[left][right] = coins
return best[0][n - 1]
Python details worth noting:
- Adding lists.
[1] + nums + [1]builds a new list. It does not changenums, so the caller's list is left alone. - Build the rows separately.
[[0] * n for _ in range(n)]creates a new row for each value ofrange(n). Writing[[0] * n] * nrepeats the same row objectntimes: afterbad[0][1] = 7every row shows[0, 7, 0]. - Ranges stop before their end.
range(left + 1, right)yields exactly the positions strictly between the two ends. - Big numbers are fine. The largest answer for 300 balloons of 100 is 298,010,100, and Python integers don't overflow anyway.
The table for [2, 4, 3]
Here values is [1, 2, 4, 3, 1]. After the loops, best holds one list per row:
[0, 0, 8, 30, 33]
[0, 0, 0, 24, 30]
[0, 0, 0, 0, 12]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
The gap-2 cells have one balloon each: best[0][2] is 1 × 2 × 4 = 8, best[1][3] is 2 × 4 × 3 = 24, and best[2][4] is 4 × 3 × 1 = 12. The cell best[0][3] is 30: the balloons 2 and 4 sit between the first 1 and the 3. With the 4 last the total is 8 + 0 + 1 × 4 × 3 = 20, and with the 2 last it is 0 + 24 + 1 × 2 × 3 = 30, so 30 is kept. The final cell, best[0][4], is 33. With the 2 last the total is 0 + 30 + 1 × 2 × 1 = 32, with the 4 last it is 8 + 12 + 1 × 4 × 1 = 24, and with the 3 last it is 30 + 0 + 1 × 3 × 1 = 33. The best balloon to burst last is the 3.
Complexity
Time: O(n³). There are about n² / 2 ranges, and each one tries up to n balloons as the last one. Counting the inner loop exactly, a row of 300 balloons runs it 4,545,100 times, close to n³ / 6.
Space: O(n²). The table best has n × n entries.
Edge cases and common mistakes
- One balloon.
[5]gives 5, as1 × 5 × 1. The loop runs once withgap = 2. - A zero balloon.
[3, 0, 4]gives 16. Bursting the 0 first pays nothing, but it makes the 3 and the 4 neighbours, which raises what the other two bursts pay. - Deciding which balloon bursts first. After a first burst, its two neighbours become adjacent, so the two sides of the row still depend on each other. The balloon that bursts last is the one that keeps the row split into two independent parts.
- A greedy order. Bursting the smallest balloon first looks natural, but for
[2, 4, 3]it collects 24 instead of 33. - Forgetting the padding. Without the added 1s, the balloons at the ends would need special cases for their missing neighbours.
- Filling long ranges first. A long range reads
bestfor shorter ones. Looping by increasing gap makes sure those are ready. - Using the wrong bounds for the parts. The parts are
best[left][last]andbest[last][right]: both keeplastas an end that stays in place, because it has not burst yet.
Testing
[2, 4, 3]gives33.[1, 8, 1]gives24.[3, 0, 4]gives16.[5]gives5.[0]gives0.[1, 1, 1, 1]gives4.
