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]
相关推荐
西门吹雪分身1 分钟前
Redis之RedLock算法以及底层原理
数据库·redis·算法
一路向北he24 分钟前
杰理10k3950温度测量
java·数据结构·算法
描绘一抹色30 分钟前
力扣-hot100(最长连续序列 - Hash)
数据结构·算法·leetcode
黄昏ivi1 小时前
事件触发控制与响应驱动控制的定义、种类及区别
人工智能·分布式·学习·算法·机器学习
温文尔雅透你娘1 小时前
摄像头在自动驾驶中的核心应用:感知算法与技术方案深度解析
人工智能·算法·计算机视觉·目标跟踪·自动驾驶
Vacant Seat1 小时前
贪心算法-跳跃游戏
算法·游戏·贪心算法
是小满满满满吗1 小时前
基础贪心算法集合2(10题)
算法·贪心算法
小林熬夜学编程1 小时前
【高阶数据结构】第三弹---图的存储与遍历详解:邻接表构建与邻接矩阵的BFS/DFS实现
c语言·数据结构·c++·算法·深度优先·图论·宽度优先
谢道韫6661 小时前
37-串联所有单词的子串
开发语言·算法·c#
爱编程的小新☆2 小时前
2025年第十六届蓝桥杯省赛JavaB组真题回顾
算法·职场和发展·蓝桥杯