Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

312. Burst Balloons #261

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

312. Burst Balloons

n 个气球,编号为0n-1,每个气球上都标有一个数字,这些数字存在数组 nums 中。

现在要求你戳破所有的气球。如果你戳破气球 i ,就可以获得 nums[left] * nums[i] * nums[right] 个硬币。 这里的 left 和 right 代表和 i 相邻的两个气球的序号。注意当你戳破了气球 i 后,气球 left 和气球 right 就变成了相邻的气球。

求所能获得硬币的最大数量。

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

Note

Tcdian commented 4 years ago

Solution

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxCoins = function(nums) {
    const dp = Array.from(new Array(nums.length + 2), () => new Array(nums.length + 2).fill(0));
    const points = [1, ...nums, 1];
    for (let i = 0; i < points.length; i++) {
        for (let j = i - 2; j >= 0; j--) {
            for (let k = j + 1; k < i; k++) {
                dp[j][i] = Math.max(dp[j][k] + dp[k][i] + points[j] * points[k] * points[i], dp[j][i]);
            }
        }
    }
    return dp[0][points.length - 1];
};
function maxCoins(nums: number[]): number {
    const dp: number[][] = Array.from(new Array(nums.length + 2), () => new Array(nums.length + 2).fill(0));
    const points = [1, ...nums, 1];
    for (let i = 0; i < points.length; i++) {
        for (let j = i - 2; j >= 0; j--) {
            for (let k = j + 1; k < i; k++) {
                dp[j][i] = Math.max(dp[j][k] + dp[k][i] + points[j] * points[k] * points[i], dp[j][i]);
            }
        }
    }
    return dp[0][points.length - 1];
};