You are given a row of boxes, where each box's color is a positive integer. You remove boxes in rounds until none are left. In each round you choose a run of contiguous boxes that all have the same color, say k boxes with k >= 1, remove them, and earn k * k points.
Return the maximum total points you can earn.
Function Signature
def remove_boxes(boxes: list[int]) -> int:
Rules
-
Equal values in
boxes
mean the same color.
-
After a removal the remaining boxes close the gap, so the boxes on either side of the removed run become neighbors and can later be removed together.
-
Every box must be removed eventually. The answer is the largest total over all removal orders.
Constraints
-
1 <= len(boxes) <= 100
-
1 <= boxes[i] <= 100
Examples
Input: boxes = [1,3,2,2,2,3,4,3,1]
Output: 23
Remove [2,2,2] for 9 points, leaving [1,3,3,4,3,1]. Remove the 4 for 1 point, then the three 3s together for 9 points, then the two 1s for 4 points: 9 + 1 + 9 + 4 = 23.
Input: boxes = [1,1,1]
Output: 9
All three boxes already form one run, so removing them at once earns 3 * 3 = 9 points.
Input: boxes = [1,2,1,2,1]
Output: 11
Removing each 2 on its own earns 2 points and joins the three 1s into one run worth 9. Grouping the two 2s instead requires removing the middle 1 first, which splits the 1s and caps the total at 4 + 1 + 4 = 9.