312. Burst Balloons

Givennballoons, indexed from0ton-1. Each balloon is painted with a number on it represented by arraynums. You are asked to burst all the balloons. If the you burst ballooniyou will getnums[left] * nums[i] * nums[right]coins. Hereleftandrightare adjacent indices ofi. After the burst, theleftandrightthen becomes adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.

Note:

  • You may imagine

    nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.

  • 0 ≤n≤ 500, 0 ≤nums[i]≤ 100

Example:

Input:[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

Thoughts:

  1. dp[left][right]: ... from subarray[left ... right]

  2. recursive function: dp[left][right] = max(..., dp[left][i], nums[left] * nums[i] * nums[right] + dp[i][right])

  3. propagating direction: from small sliding window to larger sliding window

  4. return dp[0][n-1] (from left = 0 to right n-1)

Code T: O(n^3) & S: O(n^2)

A Divide & Conquer solution

Note: In this case the reason why recursive solution with memoization is faster is because for some DP problems, we might not have to examine "all" the sub-problems, which most of the bottom-up table building iterative solutions do. In those cases, recursive solution examine less sub-problems, and that compensate for the overhead from recursion.

However, iterative solution is definitely faster than recursive solution for this problem (in Python). The reason is that they both "fill up" the same sub-solutions in the dp array, and recursion always has more overhead than iteration.

from dietpepsi's post and explanation by StrongerXi

Last updated

Was this helpful?