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]
相关推荐
luj_17681 小时前
残熵算法实时化三大瓶颈突破
c语言·开发语言·网络·经验分享·算法
mCell2 小时前
你以为短链接只是 Hash + 301/302?
后端·算法·架构
KaMeidebaby3 小时前
卡梅德生物技术快报|抗体亲和力成熟工业化调控新机制:差异性浆细胞增殖工艺优化思路
java·开发语言·人工智能·算法·机器学习·架构·spark
luj_17684 小时前
心形曲线轨迹控制三大关键技术
c语言·开发语言·c++·经验分享·算法
tmlx3I0814 小时前
高光谱拼接算法(六)RANSAC 误匹配剔除
人工智能·算法·机器学习
不相心 -w-4 小时前
基础-滑动窗口-(定长 | 不定长)
算法
醉城夜风~5 小时前
Java详解经典算法题:接雨水(三种实现方案+原理剖析)
java·开发语言·算法
ysa0510305 小时前
【板子】ST表
c++·笔记·算法·板子
CHHH_HHH5 小时前
【C++11】深入解析C++可变参数模板
开发语言·c++·算法·stl·c++11
hurrycry_小亦5 小时前
洛谷题目:P1215 [USACO1.4] 母亲的牛奶 Mother‘s Milk 题解(本题简)
算法