LeetCode 312. Burst Balloons
You are given
n
balloons, indexed from0
ton - 1
. Each balloon is painted with a number on it represented by an arraynums
. You are asked to burst all the balloons.If you burst the
ith
balloon, you will getnums[i - 1] * nums[i] * nums[i + 1]
coins. Ifi - 1
ori + 1
goes out of bounds of the array, then treat it as if there is a balloon with a1
painted on it.Return the maximum coins you can collect by bursting the balloons wisely.
This is a variant of the classical dynamic programming on intervals problem. In this question, we are picking a middle point, k, and then continuously maximizing the value by sweeping through all the possible values of it.
As for how the values are calculated, we will be taking the maximum value from the left-most index up to k and the maximum value from k up to the right-most index, both of which are already calculated in previoius iterations. Note that in our calculations, we will be leaving out the boundaries of the intervals, i.e. the left and right most index, out of the "bursting" such that the entire interval will be left only of the two, thus allowing us to carry on calculations in further iterations.
*This is of paramount importance as the calcuations of points require three ballons. By leaving the boundaries out, when we choose the middle point, the left part would be reduced to the left-most and the middle elements while the right part would be reduced to the middle and the right-most elements. This allows us to then calculated the final product. Since the maximum point can only be attained if and only if we burst the balloon in middle, the maximum points would then be calculated as the product of the left-most, middle and the right-most elements.
But then you may ask, if we are leaving out two boundary ballons out of the "bursting", then how are we going to find out the final score? How are we going to deal with the boundary cases?
Simple, just add another boundary. Since we will be treating the elements outside as a 1, we will then add a one in front and one at the back. This not only takes care of the elements out of the bounds, it also allows us to find the final product by using the same calculations stated above.
class Solution {
public:
int maxCoins(vector<int>& nums) {
if(nums.size()==1)
return nums[0];
// add boundaries
nums.insert(nums.begin(), 1);
nums.push_back(1);
int dp[nums.size()][nums.size()];
memset(dp, 0, sizeof(dp));
// loop through end index
for(int i = 3; i <= nums.size(); i++){
// loop through starting index
for(int j = 0; j <= nums.size() - i; j++){
// loop through middle point
for(int k = j + 1; k <= i + j - 2; k++){
dp[j][i+j-1] = max(dp[j][i+j-1],
// sum of two intervals
dp[j][k] + dp[k][i+j-1] +
// points of the remaining balloons
nums[j] * nums[k] * nums[i+j-1]);
}
}
}
// final result
return dp[0][nums.size()-1];
}
};
Special thanks to Justin