Skills101
← All coding problems

Burst Balloons

hardDynamic Programming+40 XPTime limit 5s

Balloons in a row have numbers a[0] … a[n−1]. Bursting balloon i earns left × a[i] × right coins, where left and right are the numbers of its current neighbours (after earlier bursts); a missing neighbour counts as 1. Burst all balloons in the best order. What is the maximum total?

Input:

  • line 1: n
  • line 2: n integers

Output: the maximum number of coins.

Constraints: 1 ≤ n ≤ 200, 0 ≤ a[i] ≤ 100.

The key insight: don't think about which balloon to burst first — think about which balloon in an interval (l, r) is burst last. Then its neighbours are exactly a[l] and a[r], and the two sides are independent: dp[l][r] = max over k of dp[l][k] + dp[k][r] + a[l]·a[k]·a[r] (with 1s padded at both ends). O(n³) interval DP.

Sample input 1

4
3 1 5 8

Sample output 1

167

Sample input 2

2
1 5

Sample output 2

10

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.