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]
相关推荐
J先生x8 分钟前
【IP101】图像分割技术全解析:从传统算法到深度学习的进阶之路
图像处理·人工智能·深度学习·学习·算法·计算机视觉
NON-JUDGMENTAL11 分钟前
第2章 算法分析基础
java·数据结构·算法
写个博客32 分钟前
代码随想录算法训练营第三十三天(补)
算法
wen__xvn33 分钟前
每日一题洛谷P1025 [NOIP 2001 提高组] 数的划分c++
数据结构·c++·算法
朱剑君1 小时前
排序算法——桶排序
算法·排序算法
MeiYu_1231 小时前
【数据结构与算法】常见排序算法详解(C++实现)
数据结构·c++·算法·排序算法
请来次降维打击!!!2 小时前
优选算法系列(8.多源BFS)
java·c++·算法·宽度优先
TextIn智能文档云平台2 小时前
TextIn ParseX重磅功能更新:支持切换公式输出形式、表格解析优化、新增电子档PDF去印章
java·图像处理·人工智能·算法·自然语言处理·pdf·ocr
LabVIEW开发2 小时前
LabVIEW温控系统热敏电阻滞后问题
算法·labview知识·labview功能
White_Can2 小时前
《数据结构:二叉搜索树(Binary Search Tree)》
数据结构·c++·算法