312. Poking Balloons
There are n
balloons, numbered to 0
, n - 1
each balloon is marked with a number, and these numbers are stored nums
in the array.
You are now asked to pop all the balloons. Pop the i
balloon and you get nums[i - 1] * nums[i] * nums[i + 1]
coins. Here i - 1
and i + 1
represent i
the serial numbers of the two adjacent balloons. If i - 1
or i + 1
is outside the bounds of the array, treat it as a 1
balloon with number .
Find the maximum number of coins that can be obtained.
Example 1:
输入:nums = [3,1,5,8]
输出:167
解释:
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
Example 2:
输入:nums = [1,5]
输出:10
hint:
n == nums.length
1 <= n <= 300
0 <= nums[i] <= 100
problem solving ideas
dynamic programming
Learning ideas: Diagram: Dynamic programming solves the problem of poking balloons, the thinking is clear and concise, and the annotations are detailed
Code
var maxCoins = function(nums) {
const newNums=[1,...nums,1];
const dp=new Array(newNums.length).fill(0).map(()=>{
return new Array(newNums.length).fill(0);
})
for(let upDownPrint=nums.length ; upDownPrint>=0; upDownPrint--){
for(let leftRightPrint=upDownPrint+1;leftRightPrint<newNums.length;leftRightPrint++){
for(let lastBall=upDownPrint+1;lastBall<leftRightPrint;lastBall++){
dp[upDownPrint][leftRightPrint]=Math.max(dp[upDownPrint][leftRightPrint],dp[upDownPrint][lastBall]+dp[lastBall][leftRightPrint]+newNums[upDownPrint]*newNums[leftRightPrint]*newNums[lastBall]);
}
}
}
return dp[0][nums.length+1];
};