Classical interval DP question.
From observation, we know the left interval and right interval are independent to each other, only and only if the common balloons of two interval didnt brust.
Here are some illustration:
[1, 3, 4, 2, 1]
left interval : [1, 3, 4]
right interval: [4, 2, 1]
unless the 4 havent brusted, the left interval scores and right interval scores are independent.
Once we have this information, rest of the operations is easy think of.
We just need to enumerate the length of big interval, and cut it off to be left interval and right interval. Our dp array would updates the optimal scores of different length of interval one by one. Thus, when we cut the interval into two parts, we are able to get the scores of these two parts imediately and we just need to calculate the scores we get from the balloons we brust where we cut the interval into two parts.
About correctness of this algorithm:
As long as we dont brust the balloon at the edge of the interval, it will not have double counting problem. you can try to illustrate the process.
You would ask how can we calculate the scores of num[0] and num[n]?
We can try to add 1 at the head of the num and the tail of the num.
Code:
class Solution {
public:
int maxCoins(vector<int>& num) {
int n = num.size();
vector<int>nums;
nums.push_back(1);
for(int i = 0; i < n; i++){
nums.push_back(num[i]);
}
nums.push_back(1);
n = nums.size();
int dp[302][302];
memset(dp, 0, sizeof(dp));
for(int len = 3; len <= n; len++){
for(int left = 0; left <= n - len; left++){
int right = left + len - 1;
for(int mid = left + 1; mid < right; mid++){
dp[left][right] = max(dp[left][right], dp[left][mid] + dp[mid][right] + nums[left]*nums[mid]*nums[right]);
}
}
}
return dp[0][n - 1];
}
};