SDE & MLE Prep

312. Burst Balloons

Problem

Balloons are painted with the numbers in nums. Bursting balloon i earns nums[left] × nums[i] × nums[right], where left and right are its current neighbours (a missing neighbour counts as 1); then they become adjacent. Return the maximum coins from bursting them all.

Example: [3,1,5,8] → 167

Constraints: n ≤ 300.

Think about the balloon burst last in (l, r) (exclusive bounds, padded with 1s): dp[l][r] = max over k of dp[l][k] + nums[l]·nums[k]·nums[r] + dp[k][r]. Fill by increasing interval length.

[1 | 3 1 5 8 | 1]      if 8 is last in (0,5): 1*8*1 + best(0..4 exclusive) + best(4..5)
answer 167 = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1

Complexity: O(n³).

class Solution:
    def maxCoins(self, nums: List[int]) -> int:
        a = [1] + nums + [1]
        n = len(a)
        dp = [[0] * n for _ in range(n)]
        for length in range(2, n):
            for l in range(n - length):
                r = l + length
                dp[l][r] = max(dp[l][k] + a[l] * a[k] * a[r] + dp[k][r] for k in range(l + 1, r))
        return dp[0][n - 1]