Skip to content

546. Remove Boxes

Array Dynamic Programming Memoization

Problem - Remove Boxes

Hard

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.

 

Example 1:

Input: boxes = [1,3,2,2,2,3,4,3,1]
Output: 23
Explanation:
[1, 3, 2, 2, 2, 3, 4, 3, 1] 
----> [1, 3, 3, 4, 3, 1] (3*3=9 points) 
----> [1, 3, 3, 3, 1] (1*1=1 points) 
----> [1, 1] (3*3=9 points) 
----> [] (2*2=4 points)

Example 2:

Input: boxes = [1,1,1]
Output: 9

Example 3:

Input: boxes = [1]
Output: 1

 

Constraints:

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

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def removeBoxes(self, boxes: List[int]) -> int:
        n = len(boxes)

        @cache
        def dfs(i: int, j: int, k: int) -> int:
            if i > j:
                return 0
            while i < j and boxes[j] == boxes[j - 1]:
                j, k = j - 1, k + 1
            result = dfs(i, j - 1, 0) + ((k + 1)**2)
            for val in range(i, j):
                if boxes[j] == boxes[val]:
                    result = max(result, dfs(val + 1, j - 1, 0) + dfs(i, val, k + 1))
            return result

        return dfs(0, n - 1, 0)

Submission Stats:

  • Runtime: 694 ms (73.15%)
  • Memory: 36.9 MB (61.35%)