CodeArchon

hard2-D Dynamic ProgrammingGoogle

Fireworks Bursting Planner

A pyrotechnician bursts a row of balloons in an order that maximizes coins = left·current·right (with implicit 1s outside).

Given nums, you may burst balloons one at a time; bursting i gives nums[i-1]*nums[i]*nums[i+1] coins (with 1 at the ends). Maximize total coins.

Choose approach

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1/6
Narrationstep 1 of 6

Padded = [1,3,1,5,8,1].

1def maxCoins(nums):
2 a = [1] + nums + [1]
3 n = len(a)
4 dp = [[0]*n for _ in range(n)]
5 for L in range(2, n):
6 for l in range(0, n - L):
7 r = l + L
8 for k in range(l + 1, r):
9 dp[l][r] = max(dp[l][r], a[l]*a[k]*a[r] + dp[l][k] + dp[k][r])
10 return dp[0][n-1]
Variables
padded=1,3,1,5,8,1

How to think about it

  1. Fixing 'last burst' decouples the two sides.
  2. Pad with 1s to simplify boundaries.

Edge cases to catch in interview

  • Single balloon n -> n.
  • Already padded case ignores padded 1s.

Examples

Example 110
{"nums":[1,5]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed