Skip to content
Problem 546 · LeetCode 546(opens in a new tab)

Remove Boxes

HardArrays

You are given a row of coloured boxes, boxes, where each colour is a positive number. In one move you pick a run of next-to-each-other boxes that all share a colour, remove the whole run, and score the square of its length: a run of 3 scores 9. The boxes on either side then close the gap.

Keep moving until no boxes are left. Return the highest total score you can reach.

Example 1

Input:  boxes = [3, 1, 1, 3, 2, 3]
Output: 14
Why:    take 2 (1), then 1 1 (4); the three 3s now touch (9)
2 more examples and the constraints

Example 2

Input:  boxes = [2, 1, 2]
Output: 5
Why:    take 1 (1), then both 2s together (4)

Example 3

Input:  boxes = [4, 4, 4, 4]
Output: 16
Why:    one move removes all four

Constraints

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

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every move on the remaining rowO(2ⁿ·n²)
  2. Interval DP with a joined countO(n⁴)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100 boxes in mixed coloursVerdict
Try every move on the remaining rowO(2ⁿ·n²)
Only for short rows
Interval DP with a joined countO(n⁴)
Best; the standard answer

n = number of boxes.

Edge cases to test

  • One box. [7] scores 1.
  • All one colour. 100 equal boxes leave in one move for 10,000 points.
  • All different colours. Nothing can join, so the score is n.
  • Same colour split many times. [5, 1, 5, 2, 5, 3, 5]: clear 1, 2 and 3 one by one, then the four 5s leave together for 3 + 16 = 19.

Common mistakes

  • Using only dp(l, r): it cannot tell how many partners box l will leave with, so it scores too low.
  • Removing the longest run first: on [3, 1, 1, 3, 2, 3] that greedy rule scores 10, not 14.
  • Saving the memo under the changed l and k after absorbing a run, instead of the key the call started with.

How to talk through it

  1. 1Clarify. Must a removed group be next to each other right now? Do boxes close the gap after a move?
  2. 2Give the brute force. Try every run, recurse on the row that is left, memo by row: exponential states.
  3. 3Find the missing state. A range alone is not enough; also track how many same-coloured boxes join box l.
  4. 4Code the two choices. Leave now for (k + 1)², or clear the middle and join a later box of the same colour.
  5. 5Test out loud. Run [2, 1, 2], all one colour, and all different colours.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?