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.
Example 1:
Input: nums = [3,1,5,8] Output: 167 Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
区间DP的经典题目
因为对区间长度有要求,至少是3,所以遍历时选择先对区间长度遍历,再对区间起点遍历。注意:在对区间起点进行遍历的时候,遍历的终点需要依据区间长度而定。
dp[i][j]为开区间i,j中能得到的最大分数。将dp[i][j]拆解为dp[i][k], dp[k][j]即可得到状态转移方程。
所以还需要一个for循环 for(i+1, j)来对dp[i][j]的所有可能拆解方案进行遍历。
class Solution:
def maxCoins(self, nums: List[int]) -> int:
size = len(nums)
arr = [0] * (size+2)
arr[0] = arr[size+1] = 1
arr[1:size+1] = nums
dp = [[0 for _ in range(size + 2)] for _ in range(size + 2)]
for l in range(3, size+3):
for i in range(size+3-l):
j = i + l - 1
for k in range(i + 1, j):
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + arr[i]*arr[j]*arr[k])
return dp[0][size+1]