Skip to content

546. Remove Boxes

Description

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

Solution: Dynamic Programming

  • Time complexity: O(n4)
  • Space complexity: O(n3)

 

JavaScript

js
/**
 * @param {number[]} boxes
 * @return {number}
 */
const removeBoxes = function (boxes) {
  const n = boxes.length;
  const dp = new Array(n)
    .fill('')
    .map(_ =>
      new Array(n)
        .fill('')
        .map(_ => new Array(n).fill(0)),
    );

  const calculatePoints = (left, right, count) => {
    if (left > right) return 0;
    if (dp[left][right][count]) return dp[left][right][count];
    const originLeft = left;
    const originCount = count;

    while (left + 1 <= right && boxes[left] === boxes[left + 1]) {
      left += 1;
      count += 1;
    }
    let result = (count + 1) ** 2 + calculatePoints(left + 1, right, 0);

    for (let index = left + 1; index <= right; index++) {
      if (boxes[left] !== boxes[index]) continue;
      const points = calculatePoints(left + 1, index - 1, 0) + calculatePoints(index, right, count + 1);

      result = Math.max(points, result);
    }
    return (dp[originLeft][right][originCount] = result);
  };

  return calculatePoints(0, n - 1, 0);
};

Released under the MIT license