Start learning free

LESSON 255 OF 314 · DYNAMIC PROGRAMMING

Burst Balloons in Go: O(n³) Interval Dynamic Programming

Practice O(n³) Read the full explanation

You get an array nums. It holds the numbers on a row of balloons, from left to right.

You burst the balloons one at a time, in any order you choose. Return the most coins you can collect.

Bursting a balloon pays its number times the numbers of its two neighbours. Its neighbours are the nearest balloons still in the row. When no balloon is left on one side, that side counts as 1.

 

Example 1:

Input: nums = [2,4,3]
Output: 33
Explanation: Burst the 4 first: 2 × 4 × 3 = 24 coins.
The row is now [2,3].
Burst the 2 next: 1 × 2 × 3 = 6 coins.
Burst the 3 last: 1 × 3 × 1 = 3 coins.
In total, 24 + 6 + 3 = 33.

Example 2:

Input: nums = [1,8,1]
Output: 24
Explanation: Burst the first 1: 1 × 1 × 8 = 8 coins.
Burst the other 1: 8 × 1 × 1 = 8 coins.
Burst the 8 last: 1 × 8 × 1 = 8 coins.
In total, 8 + 8 + 8 = 24.
Bursting the 8 first gives only 8 + 1 + 1 = 10.

Example 3:

Input: nums = [3,0,4]
Output: 16
Explanation: Burst the 0 first: 3 × 0 × 4 = 0 coins.
Burst the 3 next: 1 × 3 × 4 = 12 coins.
Burst the 4 last: 1 × 4 × 1 = 4 coins.
In total, 0 + 12 + 4 = 16.

 

Constraints:

  • nums holds 1 to 300 numbers.
  • Each number is a whole number from 0 to 100.

Note:

Your solution should run in O(n3) time. Here n is the length of nums.



Trying every order is far too slow. Ten balloons already have 3,628,800 orders.
Look at one range of the row instead, and ask which balloon in it bursts last. Until it bursts, it stands between its left part and its right part. So the two parts never touch, and each one is a smaller problem of the same kind.

Add a 1 at each end of the row, and call the new list values. Its two ends are never burst.
Let best[left][right] be the most coins from bursting every balloon strictly between left and right, while those two stay.
If balloon last bursts last in that range, its neighbours are left and right by then. It pays values[left] × values[last] × values[right]. The parts on its two sides add best[left][last] and best[last][right].
Try every last and keep the largest total. Fill the short ranges before the long ones. The answer is best[0][n - 1], where n is the length of values.

There are about n2 / 2 ranges. Each one tries up to n balloons as the last one. That is O(n3) time.
The table best takes O(n2) space.
STEP 1 OF 15
    Ctrl + Enter to check

    GO · DYNAMIC PROGRAMMING

    Burst Balloons in Go, explained

    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

    1. Pad the row. n := len(nums) + 2, and values is a slice of n ints with 1 at both ends and the balloons copied into positions 1 to n-2.
    2. Create the table. best is an n by n table: make([][]int, n) makes the outer slice, and each row needs its own make([]int, n). All zeros is already right where left and right are next to each other, since no balloon lies between them.
    3. Solve short ranges first. gap is the distance between left and right. It starts at 2, the smallest gap that holds a balloon, and goes up to n - 1. A long range uses the answers of shorter ones, so those must be ready.
    4. Choose the left end. left goes from 0 while left < n-gap, so that right := left + gap stays below n.
    5. Try each last balloon. last goes from left + 1 to right - 1. Compute coins as the two sub-ranges plus the final burst.
    6. Keep the best. If coins beats best[left][right], store it.
    7. 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, 1 is a tuple assignment: Go assigns both in one statement.
    • for i, num := range nums gives each index and value. The new slice is a separate copy, so nums itself is not changed.
    • A slice of slices is built row by row. make([][]int, n) alone leaves every row nil, and writing into best[i][j] would panic.
    • The loops use the three-part for in each of its forms. Go has no other loop keyword.
    • int is 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:

    leftrightbest[left][right]
    028
    1324
    2412
    0330
    1430
    0433

    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 left first, best[left][last] and best[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 best causes an index panic on the first write.

    Testing

    Results from running the solution:

    numsResult
    [2, 4, 3]33
    [1, 8, 1]24
    [3, 0, 4]16
    [5]5
    [0]0
    [3, 1, 5, 8]167
    [100, 100]10100
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free