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]
相关推荐
千金裘换酒4 小时前
LeetCode 移动零元素 快慢指针
算法·leetcode·职场和发展
wm10434 小时前
机器学习第二讲 KNN算法
人工智能·算法·机器学习
NAGNIP4 小时前
一文搞懂机器学习线性代数基础知识!
算法
NAGNIP4 小时前
机器学习入门概述一览
算法
iuu_star5 小时前
C语言数据结构-顺序查找、折半查找
c语言·数据结构·算法
Yzzz-F5 小时前
P1558 色板游戏 [线段树 + 二进制状态压缩 + 懒标记区间重置]
算法
漫随流水5 小时前
leetcode算法(515.在每个树行中找最大值)
数据结构·算法·leetcode·二叉树
mit6.8246 小时前
dfs|前后缀分解
算法
扫地的小何尚6 小时前
NVIDIA RTX PC开源AI工具升级:加速LLM和扩散模型的性能革命
人工智能·python·算法·开源·nvidia·1024程序员节
千金裘换酒7 小时前
LeetCode反转链表
算法·leetcode·链表