PracticeNeetCode ↗LeetCode ↗
Given n balloons with values nums, bursting balloon i earns nums[left] × nums[i] × nums[right] coins, where left and right are its current neighbors after previous bursts. Return the maximum coins obtainable by bursting every balloon.
dp[l][r] represents the max coins from bursting everything strictly between indices l and r, trying every possible choice of which balloon in that range is burst last.nums with a 1 at both ends.dp table, all zeros, sized to the padded array.(l, r), try every k strictly between them as the last balloon burst in that range.nums[l] × nums[k] × nums[r], plus whatever was already earned bursting everything in (l, k) and (k, r) — take the best k.dp[0][n-1] of the padded array.Time: O(n³) — Space: O(n²)
def maxCoins(nums: list[int]) -> int:
balloons = [1] + nums + [1]
n = len(balloons)
dp = [[0] * n for _ in range(n)]
for length in range(2, n):
for l in range(n - length):
r = l + length
for k in range(l + 1, r):
dp[l][r] = max(
dp[l][r],
dp[l][k] + balloons[l] * balloons[k] * balloons[r] + dp[k][r],
)
return dp[0][n - 1]How the solution above works, piece by piece.
dp[l][r] = the most coins from bursting all balloons strictly between l and r (the ends stay).k as the last balloon burst in that range. At that moment only l and r are left beside it, so it earns balloons[l] * balloons[k] * balloons[r], and the left and right parts are independent: dp[l][k] + dp[k][r].dp[0][n-1] is the answer. O(n³) time, O(n²) space.Running it on nums = [3, 1, 5, 8]: