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]
相关推荐
圣保罗的大教堂16 分钟前
leetcode 3531. 统计被覆盖的建筑 中等
leetcode
Data_agent31 分钟前
1688获得1688店铺列表API,python请求示例
开发语言·python·算法
2301_764441331 小时前
使用python构建的应急物资代储博弈模型
开发语言·python·算法
hetao17338371 小时前
2025-12-11 hetao1733837的刷题笔记
c++·笔记·算法
Xの哲學2 小时前
Linux电源管理深度剖析
linux·服务器·算法·架构·边缘计算
小飞Coding2 小时前
一文讲透 TF-IDF:如何用一个向量“代表”一篇文章?
算法
算家计算2 小时前
突然发布!GPT-5.2深夜来袭,3个版本碾压人类专家,打工人该怎么选?
算法·openai·ai编程
s09071363 小时前
Xilinx FPGA 中ADC 数据下变频+ CIC 滤波
算法·fpga开发·fpga·zynq
TL滕4 小时前
从0开始学算法——第十二天(KMP算法练习)
笔记·学习·算法
Math_teacher_fan4 小时前
第二篇:核心几何工具类详解
人工智能·算法