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]
相关推荐
m0_7352346044 分钟前
蓝桥杯算法实战分享:算法进阶之路与实战技巧
算法·职场和发展·蓝桥杯
程序员老周6661 小时前
矩阵补充,最近邻查找
算法·机器学习·推荐算法
_GR1 小时前
2021年蓝桥杯第十二届C&C++大学B组真题及代码
c语言·数据结构·c++·算法·蓝桥杯
奋进的小暄1 小时前
贪心算法(11)(java)加油站
算法·贪心算法
tpoog2 小时前
[贪心算法]最长回文串 && 增减字符串匹配 && 分发饼干
算法·贪心算法
Flower#3 小时前
C . Serval and The Formula【Codeforces Round 1011 (Div. 2)】
c语言·开发语言·c++·算法
大刀爱敲代码3 小时前
基础算法02——冒泡排序(Bubble Sort)
java·算法·排序算法
张琪杭3 小时前
机器学习-基于KNN算法手动实现kd树
人工智能·算法·机器学习
平乐君3 小时前
Leetcode 刷题笔记 图论part05
笔记·leetcode·图论
SuperCandyXu3 小时前
leetcode1109. 航班预订统计-medium
c++·算法·leetcode