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]
相关推荐
MicroTech202523 分钟前
MLGO微算法科技发布多用户协同推理批处理优化系统,重构AI推理服务效率与能耗新标准
人工智能·科技·算法
一匹电信狗32 分钟前
【牛客CM11】链表分割
c语言·开发语言·数据结构·c++·算法·leetcode·stl
不染尘.39 分钟前
图的邻接矩阵实现以及遍历
开发语言·数据结构·vscode·算法·深度优先
AndrewHZ1 小时前
【图像处理基石】多波段图像融合算法入门:从概念到实践
图像处理·人工智能·算法·图像融合·遥感图像·多波段·变换域
yong99901 小时前
C++语法—类的声明和定义
开发语言·c++·算法
大佬,救命!!!1 小时前
C++多线程运行整理
开发语言·c++·算法·学习笔记·多线程·新手练习
AI科技星2 小时前
基于空间螺旋运动假设的水星近日点进动理论推导与验证
数据结构·人工智能·经验分享·算法·计算机视觉
L_09072 小时前
【Algorithm】Day-10
c++·算法·leetcode
大大dxy大大3 小时前
sklearn-提取字典特征
人工智能·算法·sklearn
初学小刘3 小时前
U-Net系列算法
算法