Leetcode 312. Burst Balloons

Problem

You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.

If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.

Return the maximum coins you can collect by bursting the balloons wisely.

Algorithm

Dynamic Programming (DP). Let dp[s][t] represent the maximum number of coins that can be obtained by bursting all the balloons between index s and t.
d p [ s ] [ t ] = m a x ( d p [ s ] [ k ] + d p [ k ] [ t ] + n u m s [ s ] ∗ n u m s [ k ] ∗ n u m s [ t ] ) dp[s][t] = max(dp[s][k] + dp[k][t] + nums[s] * nums[k] * nums[t]) dp[s][t]=max(dp[s][k]+dp[k][t]+nums[s]∗nums[k]∗nums[t])

For s < k < t s < k < t s<k<t.

Code

python3 复制代码
class Solution:
    def maxCoins(self, nums: List[int]) -> int:
        nums = [1] + nums + [1]
        nlen = len(nums)
        dp = [[0] * nlen for _ in range(nlen)]
        
        for l in range(2, nlen):
            for s in range(nlen - l):
                t = s + l
                for k in range(s+1, t):
                    if dp[s][t] < dp[s][k] + dp[k][t] + nums[s] * nums[k] * nums[t]:
                        dp[s][t] = dp[s][k] + dp[k][t] + nums[s] * nums[k] * nums[t]
        
        return dp[0][nlen - 1]
相关推荐
u0109272711 小时前
C++中的RAII技术深入
开发语言·c++·算法
2401_832131952 小时前
模板错误消息优化
开发语言·c++·算法
金枪不摆鳍2 小时前
算法--二叉搜索树
数据结构·c++·算法
近津薪荼2 小时前
优选算法——双指针6(单调性)
c++·学习·算法
helloworldandy2 小时前
高性能图像处理库
开发语言·c++·算法
2401_836563182 小时前
C++中的枚举类高级用法
开发语言·c++·算法
bantinghy3 小时前
Nginx基础加权轮询负载均衡算法
服务器·算法·nginx·负载均衡
chao1898443 小时前
矢量拟合算法在网络参数有理式拟合中的应用
开发语言·算法
代码无bug抓狂人3 小时前
动态规划(附带入门例题)
c语言·算法·动态规划
weixin_445402303 小时前
C++中的命令模式变体
开发语言·c++·算法