InterviewPrepKit

Home / Coding / 2-D Dynamic Programming

Burst Balloons

hard Original ↗
Solving tips
  • Key insight: don't ask which balloon to burst first (that splits the row with a moving boundary); ask which balloon k is burst LAST in an interval, which freezes its neighbors to the fixed boundaries and makes the two sides independent.
  • Pad the array with 1 on both ends, then define dp[left][right] over the OPEN interval and use the split dp[left][right] = max over k of vals[left]*vals[k]*vals[right] + dp[left][k] + dp[k][right].
  • This is interval DP: fill by increasing interval width so both sub-intervals are ready; target O(n^3) time and O(n^2) space with no rolling-row reduction available.
  • Pitfall: treating left/right as inclusive rather than as boundaries, or forgetting the padding, which mishandles the edge balloons.

Problem

You are given n balloons in a row, each carrying a number in nums. You burst them one at a time. Bursting balloon i earns nums[i-1] * nums[i] * nums[i+1] coins, where a balloon just outside the array boundary is treated as carrying the value 1. After a balloon bursts, its neighbors become adjacent. Burst all balloons and return the maximum total coins.

Examples

  • nums = [3,1,5,8]167 — burst 1 (3·1·5=15), then 5 (3·5·8=120), then 3 (1·3·8=24), then 8 (1·8·1=8); total 15+120+24+8 = 167.
  • nums = [1,5]10 — burst 1 (1·1·5=5), then 5 (1·5·1=5); total 10.
  • nums = [7]7 — one balloon, both neighbors are the boundary 1, so 1·7·1 = 7.

Constraints

  • 1 <= n <= 300
  • 0 <= nums[i] <= 100
  • The order of bursting is what you choose to optimize; there are n! orders, so brute force is impossible even at moderate n. The n = 300 bound points at an O(n³) interval DP.

Think about it first

Hint 1 The trouble with "which balloon to burst first" is that bursting changes who is adjacent to whom, so subproblems overlap in a messy way. Try flipping the question: instead of the first balloon to burst in a range, fix the **last** one.
Hint 2 Pad the array with a `1` on each end. Consider an open interval `(left, right)` of balloons. If balloon `k` is the *last* one you burst inside it, then at that moment its only surviving neighbors are the boundaries `left` and `right`, earning `nums[left] * nums[k] * nums[right]`. Everything inside `(left, k)` and `(k, right)` was already cleared independently.
Hint 3 `dp[left][right]` = max coins from bursting every balloon strictly between `left` and `right`. Then `dp[left][right] = max over k in (left, right) of nums[left]*nums[k]*nums[right] + dp[left][k] + dp[k][right]`. Fill it by increasing interval width so both sub-intervals are ready.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.