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]
相关推荐
小O的算法实验室1 小时前
SEVC,城市灾害环境下应急物流的帕累托归档引导式多目标路径规划
算法
维克兜率天2 小时前
【维克】布林带:通道类指标的“量化基石“
人工智能·python·算法
风落青芜2 小时前
C++入门:类和对象(二)
开发语言·数据结构·c++·算法
wuyk5553 小时前
AI 时代的嵌入式该怎么学-11-C不是语法是对内存的显式建模
c语言·开发语言·stm32·单片机·嵌入式硬件·mcu·算法
吞下星星的少年·-·3 小时前
LeetCode 热题 100 最长连续序列(哈希表)
算法·leetcode·散列表
风落青芜3 小时前
C++入门:类和对象(三)
开发语言·数据结构·c++·算法
Pniubi4 小时前
力扣25.K个一组反转链表
算法·leetcode·链表
16月6日-晴4 小时前
力扣22题,括号生成
算法
老唐7775 小时前
具身智能视觉感知详解:从图像识别到机器人环境理解,核心技术、算法架构与应用实践
人工智能·深度学习·算法·机器人·大模型·具身智能