To solve this problem, we need to maximize the number of coins obtained by popping balloons arranged in a row. Each time a balloon is popped, the coins obtained are the product of the numbers on the balloon and its immediate left and right neighbors (with 1 considered as neighbors if there are none).
Approach
The optimal approach to solve this problem involves dynamic programming (DP). The key insight is to use a DP table where dp[i][j] represents the maximum coins that can be obtained by popping all balloons between indices i and j (exclusive, meaning i and j are the boundaries and not popped yet).
- Extended Array: We add 1 to both ends of the input array to handle the boundary conditions (since popping the first or last balloon in the original array will have 1 as a neighbor).
- DP Table Initialization: We initialize a 2D DP array of size
(n+2) x (n+2)(wherenis the length of the original array) with all zeros. - Recurrence Relation: For each interval length
l(from 2 ton+1), we computedp[i][j]by considering each balloonk(betweeniandj) as the last balloon to pop. The coins from poppingkarearr[i] * arr[k] * arr[j]plus the coins from the left subintervaldp[i][k]and the right subintervaldp[k][j]. - Result: The value
dp[0][n+1]gives the maximum coins for the entire array (since0andn+1are the extended boundaries).
Solution Code
def maxCoins(nums):
n = len(nums)
arr = [1] + nums + [1]
dp = [[0]*(n+2) for _ in range(n+2)]
for l in range(2, n+2): # l is j - i
for i in range(n+2 - l):
j = i + l
for k in range(i+1, j):
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + arr[i] * arr[k] * arr[j])
return dp[0][n+1]
Explanation
- Extended Array: Adding 1 to both ends simplifies the calculation for the first and last balloons in the original array.
- DP Table: The DP table
dp[i][j]is filled by considering all possible intervals. For each interval, we check all possible balloons that could be the last to pop, as this allows us to compute the coins from the left and right subintervals independently. - Time Complexity: The time complexity is
O(n^3)because we have three nested loops (for interval length, start index, and middle index). This is feasible fornup to around 300, which is typical for such problems.
This approach efficiently computes the maximum coins by leveraging dynamic programming to avoid redundant calculations and ensure optimal substructure. The result is the maximum coins obtainable by popping all balloons in the optimal order.


(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。