Problem overview
The function maxCoins gets a slice 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. Bursting a balloon pays its number times the numbers on its two neighbours, meaning the nearest balloons still in the row. When no balloon is left on one side, that side counts as 1. The function returns the most coins you can collect.
For [2, 4, 3] the answer is 33. Burst the 4 first (2 × 4 × 3 = 24 coins), leaving [2, 3]. Burst the 2 next (1 × 2 × 3 = 6), then the 3 (1 × 3 × 1 = 3). The total is 24 + 6 + 3 = 33. For [1, 8, 1] the answer is 24, and for [3, 0, 4] it is 16.
The statement asks for O(n³) time, where n is the length of nums.
Approach
Trying every order of bursting is n! orders, far too many. The difficulty is that bursting a balloon changes who the neighbours are, so the sub-problems on the left and right of a burst balloon are tangled together.
The trick is to think about the last balloon to burst in a range, not the first. Take a range of balloons strictly between two balloons left and right that stay. If balloon last bursts last in this range, every other balloon of the range is already gone when it bursts, so its neighbours are exactly left and right, and the burst pays values[left] * values[last] * values[right]. Before that, last was standing between the two parts of the range. Nothing in the left part could ever see anything in the right part, so the two parts are independent smaller problems.
That gives the recurrence for best[left][right], the most coins from bursting everything strictly between left and right:
best[left][right] = max over last of best[left][last] + best[last][right] + values[left] * values[last] * values[right]
To handle the edges, a 1 is added at each end of the row. These stand for the empty space past each end. They are never burst, so every balloon always has two neighbours.
Step by step
- Pad the row.
n := len(nums) + 2, andvaluesis a slice ofnints with 1 at both ends and the balloons copied into positions 1 ton-2. - Create the table.
bestis annbyntable:make([][]int, n)makes the outer slice, and each row needs its ownmake([]int, n). All zeros is already right whereleftandrightare next to each other, since no balloon lies between them. - Solve short ranges first.
gapis the distance betweenleftandright. It starts at 2, the smallest gap that holds a balloon, and goes up ton - 1. A long range uses the answers of shorter ones, so those must be ready. - Choose the left end.
leftgoes from 0 whileleft < n-gap, so thatright := left + gapstays belown. - Try each last balloon.
lastgoes fromleft + 1toright - 1. Computecoinsas the two sub-ranges plus the final burst. - Keep the best. If
coinsbeatsbest[left][right], store it. - Return
best[0][n-1], the range between the two added 1s, which holds every balloon.
The solution in Go
func maxCoins(nums []int) int {
n := len(nums) + 2
values := make([]int, n)
values[0], values[n-1] = 1, 1
for i, num := range nums {
values[i+1] = num
}
best := make([][]int, n)
for i := range best {
best[i] = make([]int, n)
}
for gap := 2; gap < n; gap++ {
for left := 0; left < n-gap; left++ {
right := left + gap
for last := left + 1; last < right; last++ {
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]
}
Go details worth knowing:
values[0], values[n-1] = 1, 1is a tuple assignment: Go assigns both in one statement.for i, num := range numsgives each index and value. The new slice is a separate copy, sonumsitself is not changed.- A slice of slices is built row by row.
make([][]int, n)alone leaves every rownil, and writing intobest[i][j]would panic. - The loops use the three-part
forin each of its forms. Go has no other loop keyword. intis 64 bits, so the largest possible answer cannot overflow. With 300 balloons of 100 each, the answer is 298010100.
Tracing an example
For [2, 4, 3] the padded row is [1, 2, 4, 3, 1]. The values stored in best, in the order the loops compute them, are:
| left | right | best[left][right] |
|---|---|---|
| 0 | 2 | 8 |
| 1 | 3 | 24 |
| 2 | 4 | 12 |
| 0 | 3 | 30 |
| 1 | 4 | 30 |
| 0 | 4 | 33 |
The first three rows have gap 2, so a single balloon sits between the ends. For example best[1][3] is the 4 bursting between the 2 and the 3: 2 × 4 × 3 = 24. The last row is the whole row, and its value, 33, is the answer.
Complexity
Time is O(n³): there are about n²/2 pairs of left and right, and each tries up to n choices of last. Space is O(n²) for the table.
Edge cases and common mistakes
- Choosing the first balloon instead of the last. After the first burst, two balloons that were apart become neighbours, so the left and right parts are no longer independent. Choosing the last balloon keeps them apart.
- Forgetting the two padding 1s. Balloons at the ends would need special cases, and the recurrence would not apply to the whole row.
- Wrong loop order. If the loops went over
leftfirst,best[left][last]andbest[last][right]might not be computed yet. The gap loop on the outside makes sure all shorter ranges are done. - Zeros. A balloon with 0 pays nothing when it bursts, but it still matters as a neighbour: for
[3, 0, 4]bursting the 0 first costs nothing and the result is 16. - One balloon.
[5]gives 5 (1 × 5 × 1), and[0]gives 0. - Row allocation. Missing the loop that makes each row of
bestcauses an index panic on the first write.
Testing
Results from running the solution:
| nums | Result |
|---|---|
[2, 4, 3] | 33 |
[1, 8, 1] | 24 |
[3, 0, 4] | 16 |
[5] | 5 |
[0] | 0 |
[3, 1, 5, 8] | 167 |
[100, 100] | 10100 |
