Remove Boxes — LeetCode 546 Python Solution

HardMemoizationArrayDynamic Programming
Problem
#546
Reading time
3 min

The 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.

Example

Input
boxes = [1,3,2,2,2,3,4,3,1]
Output
23
Explanation
[1, 3, 2, 2, 2, 3, 4, 3, 1]

Python solution

Python
class Solution:
    def removeBoxes(self, boxes: List[int]) -> int:
        @cache
        def dfs(i, j, k):
            if i > j:
                return 0
            while i < j and boxes[j] == boxes[j - 1]:
                j, k = j - 1, k + 1
            ans = dfs(i, j - 1, 0) + (k + 1) * (k + 1)
            for h in range(i, j):
                if boxes[h] == boxes[j]:
                    ans = max(ans, dfs(h + 1, j - 1, 0) + dfs(i, h, k + 1))
            return ans

        n = len(boxes)
        ans = dfs(0, n - 1, 0)
        dfs.cache_clear()
        return ans

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 546. Remove Boxes is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming and Memoization.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 546. Remove Boxes?
LeetCode 546. Remove Boxes is rated Hard on LeetCode.
What topics does LeetCode 546. Remove Boxes cover?
LeetCode 546. Remove Boxes is tagged Memoization, Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview