Remove Boxes

HardDynamic Programminginterval dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You have a row of boxes, where boxes[i] is the colour of the i-th box. In one move you pick a maximal run of t adjacent boxes that all share a colour, remove the whole run, and score t * t points. The boxes on either side of the removed run then become adjacent. Keep removing runs until no boxes are left. Return the maximum total score you can get. A polynomial-time solution is expected (around O(n^4) worst case).

Examples

Input: boxes = [1,3,2,2,2,3,4,3,1]
Output: 23
Remove [2,2,2] for 9, then [4] for 1. The three 3s are now adjacent, worth 9. Then remove [1,1] for 4. Total 9 + 1 + 9 + 4 = 23.
Input: boxes = [1,1,1]
Output: 9
Remove all three at once for 9.
Input: boxes = [1]
Output: 1
A single box scores 1.

Constraints

  • 1 <= boxes.length <= 100
  • 1 <= boxes[i] <= 100

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More interval dp problems