Burst Balloons
Hard
Subject: 2-D Dynamic Programming
Time Complexity
O(N^3)
Space Complexity
O(N^2)
Problem Description
Problem Statement
You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. Return the maximum coins you can collect by bursting the balloons cleverly.
Example 1:
- Input:
nums = [3,1,5,8] - Output:
167
Optimal Solution
PythonApproach: Interval DP
Add a 1 to the beginning and end of the array. dp[i][j] represents the max coins we can get from bursting balloons between i and j (exclusive). We iterate over interval lengths, and for each interval, we guess the last balloon to burst.
class Solution:
def maxCoins(self, nums: List[int]) -> int:
nums = [1] + nums + [1]
n = len(nums)
dp = [[0] * n for _ in range(n)]
for length in range(2, n):
for i in range(n - length):
j = i + length
for k in range(i + 1, j):
dp[i][j] = max(dp[i][j],
nums[i] * nums[k] * nums[j] + dp[i][k] + dp[k][j])
return dp[0][n-1]