【LeetCode】【Study Notes】312. Poke the Balloon

312. Poking Balloons

There are nballoons, numbered to 0, n - 1each balloon is marked with a number, and these numbers are stored numsin the array.

You are now asked to pop all the balloons. Pop the iballoon and you get nums[i - 1] * nums[i] * nums[i + 1]coins. Here i - 1and i + 1represent ithe serial numbers of the two adjacent balloons. If i - 1or i + 1is outside the bounds of the array, treat it as a 1balloon 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];
};

Guess you like

Origin blog.csdn.net/weixin_45944495/article/details/128323710