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.


作者声明:本文包含人工智能生成内容。