Example 1
- Input
- nums = [3, 1, 5, 8]
- Output
- 167
Burst in the order 1, 5, 3, 8 for 15 + 120 + 24 + 8 = 167.
Bursting a balloon pays the product of its number with its two live neighbours, where missing neighbours count as 1. Choose the burst order that collects the most coins across all balloons.
You are given n balloons with numbers in the array nums. Bursting balloon i pays nums[i - 1] * nums[i] * nums[i + 1] coins, where a neighbour outside the array counts as 1, and the neighbours close ranks after each burst.
Burst the balloons one by one in any order until none remain. The coins from each burst add up to a total that depends entirely on the chosen order.
Return the maximum total coins achievable over every possible burst order.
n == nums.length1 <= n <= 3000 <= nums[i] <= 100Burst in the order 1, 5, 3, 8 for 15 + 120 + 24 + 8 = 167.
Burst 1 first for 5, then 5 for 5, totalling 10.
The only balloon has missing neighbours on both sides, each counted as 1. Its forced payout is 1 * 7 * 1 = 7.
Burst the two zeroes first, earning 0 each, then burst 5 between the outside ones for 5. Bursting 5 while both zeroes remain earns 0 and leaves only zeroes, losing all 5 coins.
Removing a balloon changes which values are neighbours, so a locally large payout need not produce the largest total. On [3, 1, 5, 8], removing 1 first preserves 3 and 8 around 5 for a later payout of 120. Think backwards: if 8 is the last balloon, all earlier work happens between fixed outside boundaries of 1. The same idea applies inside any smaller interval.
Reveal Try Every Burst Order: intuition, complexity, and code
1 on both ends and fill the table from short intervals to long ones, trying every candidate for last.nums = [7], which pays 1 * 7 * 1 = 7.nums = [0, 5], where bursting the 0 first still pays 0 but unlocks the better neighbour pairing.nums = [1, 5], where bursting the 1 first (10) beats bursting the 5 first (6).1 padding and special-casing the array edges instead, which drops boundary coins.When removing an element fuses its neighbours, think backwards: fixing the last removal splits the range into independent halves made for interval DP.