Problem
You are given an arraynums where nums[i] represents the value of the i-th balloon.
When you burst a balloon, you gain
nums[left] * nums[i] * nums[right] coins, where left and right are the nearest balloons that are still present.
After bursting a balloon, it is removed from the array. Find the maximum number of coins you can collect by bursting all balloons in the optimal order.
You may assume that balloons outside the array have a value of
1.
Example 1
Input
nums = [3,1,5,8]
Output
167
Example 2
Input
nums = [1,5]
Output
10
Solution
This problem can be solved using Dynamic Programming with Memoization.The main difficulty is that bursting a balloon changes its neighboring balloons, so choosing the first balloon to burst makes the remaining problem difficult to represent.
Instead of deciding which balloon to burst first, we consider which balloon should be burst last within a given range.
We add
1 to both ends of the array. For an interval from left to right, suppose balloon k is the last balloon we burst. At that moment, all other balloons inside the interval have already been removed, so its two neighbors are simply nums[left - 1] and nums[right + 1].
Therefore, the coins gained from bursting
k last are:
nums[left - 1] * nums[k] * nums[right + 1]
The remaining balloons form two independent subproblems:
[left, k - 1] and [k + 1, right].
For every possible
k, we calculate the maximum coins obtained from the left and right intervals and add the coins from bursting k last.
The state
(left, right) represents the maximum coins that can be collected by bursting all balloons between these two indexes. We store each result in memo to avoid recalculating the same interval.
class Solution {
public int maxCoins(int[] nums) {
int n = nums.length;
int[] balloons = new int[n + 2];
balloons[0] = 1;
balloons[n + 1] = 1;
for (int i = 0; i < n; i++) {
balloons[i + 1] = nums[i];
}
Integer[][] memo = new Integer[n + 2][n + 2];
return maxCoins(balloons, 1, n, memo);
}
private int maxCoins(
int[] nums, int left, int right, Integer[][] memo) {
if (left > right)
return 0;
if (memo[left][right] != null)
return memo[left][right];
int max = 0;
for (int k = left; k <= right; k++) {
int coins = nums[left - 1] * nums[k] * nums[right + 1]
+ maxCoins(nums, left, k - 1, memo)
+ maxCoins(nums, k + 1, right, memo);
max = Math.max(max, coins);
}
return memo[left][right] = max;
}
}
Complexity
There areO(n²) possible intervals represented by (left, right). For each interval, we try every possible balloon as the last balloon to burst, which takes O(n). Therefore, the time complexity is O(n³).
The memoization array stores
O(n²) states, and the recursion stack can grow up to O(n). Therefore, the extra space complexity is O(n²).
Comments
No comments yet. Ask a question or share what helped.