CodingNodes / 2-D Dynamic Programming / Burst Balloons System design Space play · ←→ step · R restart

Problem

A row of balloons is numbered 0 to n - 1, and balloon i holds the number nums[i]. You burst every balloon, one at a time. Bursting balloon i earns left · nums[i] · right coins, where left and right are the numbers on the balloons that are currently next to it (burst balloons are gone, so the neighbours change).

If there is no neighbour on a side, treat it as a balloon holding 1. Return the largest total number of coins you can earn.

Constraints

  • 1 ≤ nums.length ≤ 300
  • 0 ≤ nums[i] ≤ 100

Examples: pick one to animate

Solutions

TimeO(n³) SpaceO(n²)

Time: There are O(n²) gaps (left, right) and each tries up to n balloons as the last one, in constant time per try.

Space: The table has (n + 2) · (n + 2) cells.

Thinking about which balloon bursts first is a trap: afterwards the neighbours of the other balloons change. Think about which balloon bursts last in a gap between two fixed balloons left and right. When it bursts, everything else between them is already gone, so its neighbours are exactly left and right, and the two sides never interact. So dp[left][right] is the best over all k of dp[left][k] + vals[left] · vals[k] · vals[right] + dp[k][right]. Fill gaps from short to long, with a padding 1 at each end.