Remove Boxes - Problem

You are given several boxes with different colors represented by different positive numbers.

You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points.

Return the maximum points you can get.

Input & Output

Example 1 — Basic Case
$ Input: boxes = [1,3,2,2,2,3,4,3,1]
Output: 23
💡 Note: Remove three 2s (3×3=9 points), then remove two 3s (2×2=4 points), then remove remaining boxes one by one. Total: 9+4+1+1+1+1+1+1+1+1+1+1 = 23 points.
Example 2 — All Same Color
$ Input: boxes = [1,1,1]
Output: 9
💡 Note: Remove all three boxes at once: 3×3 = 9 points.
Example 3 — Single Box
$ Input: boxes = [1]
Output: 1
💡 Note: Only one box to remove: 1×1 = 1 point.

Constraints

  • 1 ≤ boxes.length ≤ 100
  • 1 ≤ boxes[i] ≤ 100

Visualization

Tap to expand
INPUTALGORITHMRESULT132223431Colored boxes array[1,3,2,2,2,3,4,3,1]Goal: Remove all boxesk consecutive same-colorboxes give k² points12343D DP State Spacedp[i][j][k] = max pointsConsider two options:• Remove end + extras• Split at matching colorChoose maximum pointsfrom all possibilities23POINTSMaximum achievablepoints with optimalremoval strategyExample optimal path:Remove 3 twos: 9 ptsThen others: 14 ptsKey Insight:Sometimes skip over different-colored boxes to collect more of the same color later,since k boxes removed together give k² points (exponential benefit).TutorialsPoint - Remove Boxes | 3D Dynamic Programming
Asked in
Google 15 Amazon 8 Microsoft 5
18.5K Views
Medium Frequency
~45 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen