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]
相关推荐
纪元A梦13 分钟前
分布式拜占庭容错算法——权益证明(PoS)算法详解
java·分布式·算法
GalaxyPokemon42 分钟前
LeetCode - 144. 二叉树的前序遍历
算法·leetcode·职场和发展
帮关下月亮1 小时前
Python 训练营打卡 Day 33-神经网络
python·神经网络·算法
合合技术团队1 小时前
TextIn OCR Frontend前端开源组件库发布!
大数据·人工智能·算法
zstar-_1 小时前
【Ragflow】25.Ragflow-plus开发日志:excel文件解析新思路/公式解析适配
人工智能·算法·excel
开开心心就好1 小时前
小巧实用,Windows文件夹着色软件推荐
java·开发语言·前端·决策树·c#·ocr·动态规划
Jasmine_llq2 小时前
《CF912E Prime Gift》
算法·优先队列(最小堆)·集合去重
Dovis(誓平步青云)5 小时前
C++ Vector算法精讲与底层探秘:从经典例题到性能优化全解析
开发语言·c++·经验分享·笔记·算法
编程绿豆侠10 小时前
力扣HOT100之多维动态规划:62. 不同路径
算法·leetcode·动态规划
鑫鑫向栄10 小时前
[蓝桥杯]剪格子
数据结构·c++·算法·职场和发展·蓝桥杯