817. Balloon Popping

Hard7.5 points estimatedArrayDynamic Programming3 hints

A fireworks crew has a row of shells, shell i carrying a charge balloons[i]. Detonating shell i pays out left * balloons[i] * right points, where left and right are the charges of the nearest shells still standing on either side; a missing neighbour counts as charge 1. After a detonation the row closes up around the gap.

Detonate every shell, in an order of your choice, and return the largest total number of points. An empty row is not given. Charges may be 0.

Aim for time O(n^3) and space O(n^2), where n is the number of shells.

Example 1

Input:
balloons = [3,8,2,6]
Output:
264
Explanation:

Detonate the 2 first (8*2*6 = 96), then the 8 (3*8*6 = 144), then the 3 (1*3*6 = 18) and finally the 6 (6), for a total of 264.

Example 2

Input:
balloons = [5,1,4]
Output:
45
Explanation:

Pop the 1 first for 5*1*4 = 20, then the 4 for 5*4 = 20 and the 5 for 5, total 45; other orders do worse.

Constraints

1 ≤ balloons.length ≤ 300

0 ≤ balloons[i] ≤ 100

The answer fits in a 32-bit signed integer.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n^3)
Space
O(n^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…