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 numsi - 1 * numsi * numsi + 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 dpst 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 ) dpst = max(dpsk + dpkt + numss * numsk * numst) dpst=max(dpsk+dpkt+numss∗numsk∗numst)

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]
相关推荐
小O的算法实验室2 小时前
IEEE TASE,基于MPC的多无人机协同搜索竞争群体优化方法
算法
Tbisnic3 小时前
BGE-M3 算法详解:从模型架构到三种检索方式的数学原理
算法·自然语言处理·大模型·bert·transformer·注意力机制
Brilliantwxx4 小时前
【算法从零到千】【55-58】哈希位图+常见数学运算 接口
算法
空堂与归5 小时前
用户分群找不到规律?用K-Means聚类算法自动发现数据模式
算法·机器学习·kmeans·聚类
动词ing5 小时前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习5 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
一只小小的芙厨6 小时前
基础数论总结
笔记·学习·算法
夜不会漫长7 小时前
C++入门(1)
开发语言·c++·算法
wen_zhufeng8 小时前
IndexTTS 2.5 技术报告
人工智能·算法·机器学习
大熊背9 小时前
树莓派相机自动白平衡详解(四)
算法·树莓派·白平衡·isppipeline