InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 2-D Dynamic Programming

Burst Balloons

hard Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug