312. Burst Balloons
Difficulty: Hard
Topics: Divide and Conquer, Dynamic Programming
Similar Questions:
Problem:
Given n
balloons, indexed from 0
to n-1
. Each balloon is painted with a number on it represented by array nums
. You are asked to burst all the balloons. If the you burst balloon i
you will get nums[left] * nums[i] * nums[right]
coins. Here left
and right
are adjacent indices of i
. After the burst, the left
and right
then becomes adjacent.
Find the maximum coins you can collect by bursting the balloons wisely.
Note:
- You may imagine
nums[-1] = nums[n] = 1
. They are not real therefore you can not burst them. - 0 ≤
n
≤ 500, 0 ≤nums[i]
≤ 100
Example:
Input:[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
Solutions:
class Solution {
public:
int maxCoins(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
if (n == 1) return nums[0];
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int i = 1; i < n - 1; ++i) {
dp[i][i] = nums[i] * nums[i-1] * nums[i+1];
}
dp[0][0] = nums[0] * nums[1];
dp[n-1][n-1] = nums[n-2] * nums[n-1];
for (int l = 2; l <= n; ++l) {
for (int i = 0; i < n; ++i) {
if (i + l - 1 >= n) break;
for (int mid = i; mid <= i + l - 1; ++mid) {
dp[i][i + l - 1] = max(dp[i][i + l - 1], nums[mid] * (i - 1 >= 0 ? nums[i-1] : 1) * (i + l < n ? nums[i + l] : 1)
+ (mid - 1 >= i ? dp[i][mid - 1] : 0) + (mid + 1 <= i + l - 1 ? dp[mid + 1][i + l - 1] : 0));
}
}
}
return dp[0][n-1];
}
};