AlgoInsight

DSA problem

Remove Boxes

Hard2D Grid DPPattern: 2D Grid DPtop600AmazonMicrosoftGoogleBloombergApple

You are given an array of boxes, where each entry is a positive integer color. You may repeatedly remove a contiguous run of boxes of the same color, gaining k * k points if the run has length k. The remaining boxes close up after each removal. Return the maximum number of points you can collect after removing every box.

The naive greedy "always remove the longest current run" is wrong: sometimes it pays to leave a run intact so that later, two split runs of the same color reunite into a longer run. Quadratic scoring means combining a 3-run with a 2-run after deletions in between can yield 5^2 = 25 rather than 3^2 + 2^2 = 13.

The classic DP is three-dimensional. Define dp[i][j][k] = maximum score from boxes [i..j] when there are k additional boxes of the same color as boxes[i] already attached to the left of i (a "prefix" of equal color that will be removed together when the i-run is eventually removed). Two recurrences:

  1. Remove the prefix run with boxes[i]: pay (k + 1)^2 for those k + 1 boxes, then recurse on dp[i + 1][j][0].
  2. For each m in (i, j] with boxes[m] == boxes[i], instead of taking the prefix now, splice the boxes (i, m) away first and merge with the m-run: dp[i + 1][m - 1][0] + dp[m][j][k + 1].

Take the maximum of all options. Memoize. The answer is dp[0][n - 1][0]. With memoization, the complexity is bounded by O(n^4) time and O(n^3) space — tight but practical for the constraint n <= 100.

Examples

Example 1
Input: boxes = [1,3,2,2,2,3,4,3,1]
Output: 23
Explanation: Optimal removals include leaving the 1s and 3s to combine after the middle is cleared. The maximum total is 23.
Example 2
Input: boxes = [1,1,1]
Output: 9
Explanation: Remove all three at once: 3 * 3 = 9.
Example 3
Input: boxes = [1]
Output: 1
Explanation: Single box gives 1 * 1 = 1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraydynamic-programmingmemoization

Browse all DSA problems