Remove Boxes

Hard Dynamic Programming Interval DP

Remove Boxes is a hard dynamic programming problem solved with the interval dp pattern. The best approach, optimal (memoised dp[l][r][k]), runs in O(n⁴) time and O(n³) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (try every removal order) up.

Problem

You have a row of coloured boxes, given as an array boxes where each number stands for a colour.

In one move you pick a group of neighbouring boxes that all have the same colour, say k of them, and take them out of the row. That move earns k · k points. The boxes on both sides of the gap then slide together and become neighbours, which may join boxes of the same colour into a longer group.

Keep making moves until the row is empty. Return the largest total score you can collect.

Examples

Example 1

Input
boxes = [1, 2, 2, 1, 3, 1]
Output
14
Why
Take out the two 2's first for 2 · 2 = 4 points, leaving [1, 1, 3, 1]. Take out the 3 for 1 point, leaving [1, 1, 1]. Those three 1's now touch and are worth 3 · 3 = 9. Total 4 + 1 + 9 = 14.

Example 2

Input
boxes = [3, 1, 3, 2, 3]
Output
11
Why
Remove the 1 and the 2 one at a time (1 point each). The three 3's then form a single run worth 9. Total 11. Removing the 3's early would split them into runs of length 1 and lose points.

Example 3

Input
boxes = [4, 4, 4]
Output
9
Why
The whole row is already one run of length 3, worth 3 · 3 = 9.

Constraints

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

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (try every removal order)O(n! · n)O(n²)
Recursion on (l, r, k)ExponentialO(n)
Optimal (memoised dp[l][r][k])O(n⁴)O(n³)

1Brute force (try every removal order)

TimeO(n! · n)In the worst case every box is its own run, so the first move has n choices, the next n - 1 and so on, and each call copies a list of up to n boxes.
SpaceO(n²)The recursion is at most n levels deep and each level keeps a list of up to n boxes.

Simulate the game. In the current row, every maximal run of equal boxes is a possible move. Try each one: score its length squared, glue the two sides together, and solve the shorter row recursively. Taking only part of a run is never better, because the leftover boxes of that run would only earn less on their own, so maximal runs are enough.

  1. Copy the boxes into a list.
  2. Scan the list run by run. For a run from i to j - 1, build the row without it and recurse.
  3. The value of that move is (j - i)² plus the best score of the shorter row.
  4. Return the best move; an empty row is worth 0.
class Solution {
    public int removeBoxes(int[] boxes) {
        List<Integer> row = new ArrayList<>();
        for (int b : boxes) row.add(b);
        return best(row);
    }

    private int best(List<Integer> row) {
        int res = 0;
        int i = 0;
        while (i < row.size()) {
            int j = i;
            while (j < row.size() && row.get(j).equals(row.get(i))) j++;
            List<Integer> rest = new ArrayList<>(row.subList(0, i));
            rest.addAll(row.subList(j, row.size()));
            res = Math.max(res, (j - i) * (j - i) + best(rest));
            i = j;
        }
        return res;
    }
}

2Recursion on (l, r, k)

TimeExponentialWithout a memo the same (l, r, k) triples are solved again and again from different branches, and the number of branches grows exponentially.
SpaceO(n)Only the recursion stack, at most about n calls deep.

Describe a sub-game by three numbers instead of a whole row. f(l, r, k) is the best score for boxes[l..r] when k more boxes of the same colour as boxes[l] are already stuck to its left (they were brought there by earlier moves). Box l has two futures. Either it leaves now together with its k partners, for (k + 1)² points, and we solve f(l + 1, r, 0). Or it waits for a later box m of the same colour: we first clear everything strictly between l and m, which is the independent game f(l + 1, m - 1, 0), and then box l and its partners are glued onto m, giving f(m, r, k + 1).

  1. If l > r the range is empty: return 0.
  2. While boxes[l + 1] equals boxes[l], move l right and add one to k (equal neighbours always leave together).
  3. Option 1: (k + 1)² + f(l + 1, r, 0).
  4. Option 2: for every m in (l, r] with boxes[m] == boxes[l], f(l + 1, m - 1, 0) + f(m, r, k + 1).
  5. Return the larger value; the answer is f(0, n - 1, 0).
class Solution {
    private int[] b;

    public int removeBoxes(int[] boxes) {
        b = boxes;
        return f(0, boxes.length - 1, 0);
    }

    // best score for b[l..r] when k boxes equal to b[l] are glued to its left
    private int f(int l, int r, int k) {
        if (l > r) return 0;
        while (l < r && b[l + 1] == b[l]) {
            l++;
            k++;
        }
        int res = (k + 1) * (k + 1) + f(l + 1, r, 0);
        for (int m = l + 1; m <= r; m++) {
            if (b[m] == b[l]) res = Math.max(res, f(l + 1, m - 1, 0) + f(m, r, k + 1));
        }
        return res;
    }
}

3Optimal (memoised dp[l][r][k])

TimeO(n⁴)There are at most n³ states (l, r, k), and each one loops over up to n positions m.
SpaceO(n³)The memo has n · n · n entries (one million ints for n = 100), plus a recursion stack of depth O(n).

The recursion only ever asks about triples with 0 <= l, r < n and 0 <= k < n, so there are at most n³ different questions. Store each answer in a three-dimensional memo the first time it is computed and return it straight away after that. The run compression happens before the memo lookup, so the key is the compressed (l, r, k).

  1. memo[l][r][k] = 0 means not computed yet (every real answer is at least 1, because a non-empty range always scores).
  2. In f(l, r, k): return 0 for an empty range, then compress equal neighbours into k.
  3. If memo[l][r][k] is set, return it.
  4. Otherwise compute the two options exactly as in the plain recursion, store the best in memo[l][r][k] and return it.
class Solution {
    private int[] b;
    private int[][][] memo;

    public int removeBoxes(int[] boxes) {
        int n = boxes.length;
        b = boxes;
        memo = new int[n][n][n];
        return f(0, n - 1, 0);
    }

    // best score for b[l..r] when k boxes equal to b[l] are glued to its left
    private int f(int l, int r, int k) {
        if (l > r) return 0;
        while (l < r && b[l + 1] == b[l]) {
            l++;
            k++;
        }
        if (memo[l][r][k] > 0) return memo[l][r][k];
        int res = (k + 1) * (k + 1) + f(l + 1, r, 0);
        for (int m = l + 1; m <= r; m++) {
            if (b[m] == b[l]) res = Math.max(res, f(l + 1, m - 1, 0) + f(m, r, k + 1));
        }
        memo[l][r][k] = res;
        return res;
    }
}

Edge cases to test

  • A single box (the answer is 1)
  • Every box has the same colour (the answer is n · n)
  • All colours different (every box is removed alone, the answer is n)
  • Two boxes of one colour separated by a long run of other colours, which should be cleared first
  • Alternating colours such as [1, 2, 1, 2, 1], where waiting to join boxes beats taking the biggest run now
  • A colour whose boxes are already adjacent, so the run can be compressed before branching

Hints

Hint 1

A greedy choice such as taking the longest run first fails. Try [1, 2, 1, 2, 1]: what should go first so that the 1's end up together?

Hint 2

A state of just (l, r) for the subarray boxes[l..r] is not enough. The best way to clear boxes[l..r] depends on how many boxes of the same colour as boxes[l] are waiting to be joined to it from outside.

Hint 3

Let f(l, r, k) be the best score for boxes[l..r] when k extra boxes equal to boxes[l] are already glued to its left. Either remove boxes[l] with its k partners now, or pick a later m with boxes[m] == boxes[l], clear everything between l and m first, and carry k + 1 boxes into f(m, r, k + 1).

FAQ

What is the best time complexity for Remove Boxes?

Optimal (memoised dp[l][r][k]) runs in O(n⁴) time and O(n³) extra space. There are at most n³ states (l, r, k), and each one loops over up to n positions m.

Which pattern does Remove Boxes use?

It is a dynamic programming problem that uses the interval dp pattern. Other problems with the same pattern: Matrix Chain Multiplication, Burst Balloons, Predict the Winner.

Is there a brute force solution for Remove Boxes?

Yes. Brute force (try every removal order) takes O(n! · n) time and O(n²) space. Simulate the game.

Which edge cases should I test for Remove Boxes?

A single box (the answer is 1); Every box has the same colour (the answer is n · n); All colours different (every box is removed alone, the answer is n); Two boxes of one colour separated by a long run of other colours, which should be cleared first; Alternating colours such as [1, 2, 1, 2, 1], where waiting to join boxes beats taking the biggest run now; A colour whose boxes are already adjacent, so the run can be compressed before branching.