312. Burst Balloons
Description
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. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.
Return the maximum coins you can collect by bursting the balloons wisely.
Example 1:
Input: nums = [3,1,5,8] Output: 167 Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
Example 2:
Input: nums = [1,5] Output: 10
Constraints:
n == nums.length1 <= n <= 3000 <= nums[i] <= 100
Solutions
Solution 1: Dynamic Programming
Thinking
The burst order changes neighbors, so searching by burst sequence revisits the same open intervals. Padding \(1\) at both ends fixes the multipliers on the boundary.
If \(k\) is the last balloon burst in the open interval \((i,j)\), the two sides do not interact and we add \(arr[i]\cdot arr[k]\cdot arr[j]\). Let \(f[i][j]\) be the best score of clearing \((i,j)\); fill by increasing width (\(i\) decreasing, \(j\) increasing). The answer is \(f[0][n+1]\).
Let's denote the length of the array nums as \(n\). According to the problem description, we can add a \(1\) to both ends of the array nums, denoted as arr.
Then, we define \(f[i][j]\) as the maximum number of coins we can get by bursting all the balloons in the interval \([i, j]\). Therefore, the answer is \(f[0][n+1]\).
For \(f[i][j]\), we enumerate all positions \(k\) in the interval \([i, j]\). Suppose \(k\) is the last balloon to burst, then we can get the following state transition equation:
In implementation, since the state transition equation of \(f[i][j]\) involves \(f[i][k]\) and \(f[k][j]\), where \(i < k < j\), we need to traverse \(i\) from large to small and \(j\) from small to large. This ensures that when calculating \(f[i][j]\), \(f[i][k]\) and \(f[k][j]\) have already been calculated.
Finally, we return \(f[0][n+1]\).
The time complexity is \(O(n^3)\), and the space complexity is \(O(n^2)\). Where \(n\) is the length of the array nums.
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |