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 — Strategic Grouping
$ Input: boxes = [1,3,2,2,2,3,4,3,1]
Output: 23
💡 Note: Remove [2,2,2] first (9 points), then [3,3,3] becomes consecutive (9 points), then [1] (1 point), [4] (1 point), [1] (1 point). Total: 9 + 9 + 1 + 1 + 1 = 21. But optimal is actually removing in order to get [3,3] then single [3] to group later.
Example 2 — Simple Case
$ Input: boxes = [1,1,1]
Output: 9
💡 Note: All boxes are the same color. Remove all three at once: 3² = 9 points.
Example 3 — No Grouping Possible
$ Input: boxes = [1,2,3,4,5]
Output: 5
💡 Note: All boxes are different colors, so we can only remove them one by one: 1² + 1² + 1² + 1² + 1² = 5 points.

Constraints

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

Visualization

Tap to expand
Remove Boxes: Strategic Removal for Maximum PointsInput:13311Strategy:1. Remove [3,3] → 2² = 4 points2. Now [1,1,1] are consecutive → 3² = 9 pointsTotal: 4 + 9 = 13 pointsNaive approach:Remove each group separately[1]:1 + [3,3]:4 + [1,1]:4 = 9Key: Sometimes remove other colors first to group same colors!Maximum Points: 13
Understanding the Visualization
1
Input
Array of colored boxes with removal rules
2
Strategy
Group same colors for k² bonus points
3
Output
Maximum possible points
Key Takeaway
🎯 Key Insight: Strategic removal order can group distant same-colored boxes together for exponentially higher scores
Asked in
Google 15 Facebook 12 Amazon 8
25.0K Views
Medium Frequency
~35 min Avg. Time
890 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