822. Box Removal Points

A warehouse robot faces a row of crates, boxes[i] being the colour code of crate i. In one move it picks a run of one or more adjacent crates that all share a colour, removes them and earns k * k points, where k is the number of crates removed. The row closes up, so crates that were separated can become neighbours.

Keep moving until the row is empty and return the maximum total number of points. The robot may remove only part of a longer run if it wishes.

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

Example 1

Input:
boxes = [5,2,5,7,5,2]
Output:
12
Explanation:

Remove the first 2 and the 7 (1 + 1 points) to bring three 5s together, take them for 9, then the last 2 for 1: 12 in total.

Example 2

Input:
boxes = [4,6,4,4,6]
Output:
11
Explanation:

Remove the first 6 (1 point) to join three 4s for 9, then the last 6 (1 point): 11 total.

Constraints

1 ≤ boxes.length ≤ 60

1 ≤ boxes[i] ≤ 100

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,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

Expected complexity

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

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…