#312
Burst Balloons
HardArrayDynamic ProgrammingDynamic ProgrammingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n³) |
| Space | O(n) | O(n²) |
💡
Intuition
Time O(n³)Space O(n²)
The optimal solution uses dynamic programming to avoid recalculating results for subproblems. We build a DP table where each entry represents the maximum coins that can be collected by bursting balloons between two indices.
⚙️
Algorithm
3 steps- 1Step 1: Create a DP array where dp[i][j] represents the maximum coins obtainable by bursting all balloons between indices i and j.
- 2Step 2: Iterate over all possible lengths of balloon segments from 1 to n.
- 3Step 3: For each segment, calculate the maximum coins by considering each balloon as the last one to burst in that segment and update the DP table accordingly.
solution.py10 lines
1def maxCoins(nums):
2 nums = [1] + nums + [1]
3 n = len(nums)
4 dp = [[0] * n for _ in range(n)]
5 for length in range(1, n - 1):
6 for left in range(1, n - length):
7 right = left + length - 1
8 for i in range(left, right + 1):
9 dp[left][right] = max(dp[left][right], dp[left][i - 1] + dp[i + 1][right] + nums[left - 1] * nums[i] * nums[right + 1])
10 return dp[1][n - 2]ℹ
Complexity note: The time complexity is O(n³) due to the three nested loops: one for the length of the segment, one for the left boundary, and one for the last balloon to burst. The space complexity is O(n²) for storing the DP table.
- 1Understanding the problem requires recognizing the impact of the order of bursting balloons.
- 2Dynamic programming is effective for problems with overlapping subproblems and optimal substructure.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.