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:
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
class Solution {
public:
int maxCoins(std::vector<int>& nums) {
auto balloons = std::vector<int>(nums.size() + 2);
balloons[0] = balloons[balloons.size() - 1] = 1;
for(int i = 1; i < balloons.size() - 1; i++) {
balloons[i] = nums[i - 1];
}
auto dp = std::vector<std::vector<int>>(balloons.size(), std::vector<int>(balloons.size(), 0));
for(int length = 2; length < balloons.size(); length++) {
for(int left = 0; left + length < balloons.size(); left++) {
int right = left + length;
for(int i = left + 1; i < right; i++) {
dp[left][right] = std::max(dp[left][right], balloons[left] * balloons[i] * balloons[right] + dp[left][i] + dp[i][right]);
}
}
}
return dp[0][balloons.size() -1];
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有