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]
相关推荐
Dola_Zou5 小时前
工厂智能排产软件算法保护与按产线计费实战
算法·自动化·软件工程·软件加密
啦啦啦啦啦zzzz6 小时前
Logger的组装(c++20)
c++·算法·c++20
尾善爱看海7 小时前
前端算法与手写题集
前端·算法
程序员阿鹏8 小时前
为什么MySQL InnoDB选择B+树?
数据结构·数据库·b树·sql·mysql·算法·缓存
AI 思录8 小时前
Prompt 事故档案(八):日常表达被标为“待校准”,AI 的爹味语法从哪里来
大数据·人工智能·算法·prompt·用户体验·ai合规
月光船幽幽8 小时前
跨范式映射的稳定接口设计
人工智能·python·算法
2601_9657422210 小时前
全媒体运营与短视频代运营,两者有什么区别?
大数据·数据结构·人工智能·算法·ai·媒体
wordbaby11 小时前
混合检索:两全其美的艺术
人工智能·算法
彧azz11 小时前
数据结构:关于图的学习
c语言·数据结构·笔记·学习·算法
热心网友俣先生11 小时前
A题-药材的烘干问题-题意逐句翻译
算法·数学建模