Start learning free

LESSON 539 OF 673 · DYNAMIC PROGRAMMING

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

Practice O(n³) Read the full explanation

You get a list 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 10
    Ctrl + Enter to check

    PYTHON · DYNAMIC PROGRAMMING

    Burst Balloons in Python, explained

    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

    1. Pad the row. values = [1] + nums + [1] joins the three lists into one new list.
    2. Store the length. n = len(values), which is two more than the number of balloons.
    3. Create the table. best has n rows of n zeros. Neighbouring positions have no balloon between them, so 0 is already right for them.
    4. 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.
    5. Loop over the left end: for left in range(n - gap). The right end, left + gap, must stay below n.
    6. Compute the right end: right = left + gap.
    7. 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.
    8. Add up the coins: best[left][last] + best[last][right] for the two parts, plus values[left] * values[last] * values[right] for the final burst.
    9. Keep the best: if coins beats best[left][right], store it.
    10. 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 change nums, 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 of range(n). Writing [[0] * n] * n repeats the same row object n times: after bad[0][1] = 7 every 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, as 1 × 5 × 1. The loop runs once with gap = 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 best for shorter ones. Looping by increasing gap makes sure those are ready.
    • Using the wrong bounds for the parts. The parts are best[left][last] and best[last][right]: both keep last as an end that stays in place, because it has not burst yet.

    Testing

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