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.
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
Input: nums = [1,5]
Output: 10
n == nums.length1 <= n <= 3000 <= nums[i] <= 100The key observation in this problem is that the order of bursting balloons does not matter globally, but it matters locally for a particular subproblem. We can think of each balloon as contributing coins when it is the last balloon of any subsequence to be burst. We can use dynamic programming to solve this by dividing the problem into subproblems, where we consider bursting a balloon last in a specific range, and compute the maximum coins obtainable.
Let's use a dynamic programming table dp where dp[left][right] represents the maximum coins obtainable by bursting all the balloons between index left and right (exclusive).
nums with additional boundary balloons (values 1 at both ends), because the edge balloons behave as if they are surrounded by 1.maxCoins(left, right) which uses memoization to store already computed results.i between left and right, calculate the coins gained by making it the last burst balloon, plus the resulting coins from the two partitions (left, i) and (i, right).maxCoins(left, right).This approach is similar to the memoization approach, but we fill up our table in a bottom-up manner instead. We compute the solution for smaller subproblems first and use them to build up the solution for larger subproblems.
nums with boundary balloons.dp[i][j] will represent the maximum coins obtainable by bursting all the balloons between index i and j (exclusive).dp[i][j] for subproblems of increasing size.k in current subproblem, compute maximum coins by bursting the k-th balloon last in its section.