Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 312 Burst Balloons - Implementation

The code

Pad the array with 11s: new_nums = [1] + nums + [1]. Now work with indices 00 to n+1n+1.

function maxCoins(nums)
    a := [1] + nums + [1]
    m := length of a
    dp := 2D array [m][m], all 0
    for gap from 2 to m - 1
        for i from 0 to m - gap - 1
            j := i + gap
            for k from i + 1 to j - 1
                coins := a[i] * a[k] * a[j] + dp[i][k] + dp[k][j]
                dp[i][j] := max(dp[i][j], coins)
    return dp[0][m-1]

The answer is dp[0][n+1]dp[0][n+1]. Balloon kk is the last one burst in the interval (i,j)(i, j), so a[i]a[i] and a[j]a[j] are still present as neighbors.

Time complexity: O(n3)O(n^3).

Space complexity: O(n2)O(n^2) for the DP table.