Question

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 (composed of k boxes, k >= 1), remove them and get k*k points. Find the maximum points you can get.

Example 1:
Input:

[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)

Note: The number of boxes n would not exceed 100.

Solution:

  • Method 1: dp Imgur
    • dp[i][j][k]: represents the maximum score from index i to j and k means the number of boxes[j] appended after index j.
    • Example [A, B, A, A, A] : dp[0][0][3] = 17 => (1 + 16)
    • State transfer function:
      • case 1: dp[i][j][k] = dp[i][j - 1][0] + (k + 1) ^ 2 -> This means we merge boxes[j] with the following boxes[j]
      • case 2: dp[i][j][k] = dp[i][p][k + 1] + dp[p + 1][j - 1][0] where i <= p < j && boxes[p] == boxes[j]
        • dp[i][p][k + 1]: since boxes[p] == boxes[j], so k + 1 means the previous k and the boxes[j].
        • dp[p + 1][j - 1][0]: the max score between p + 1 and j - 1.
    • Final result: dp[0][len - 1][0].
        class Solution {
        private int[][][] dp;
        public int removeBoxes(int[] boxes) {
            int len = boxes.length;
            dp = new int[len][len][len];
            return dfs(boxes, 0, len - 1, 0);
        }
        private int dfs(int[] boxes, int i, int j, int k){
            if(i > j) return 0;
            if(dp[i][j][k] > 0) return dp[i][j][k];
            dp[i][j][k] = dfs(boxes, i, j - 1, 0) + (k + 1) * (k + 1);
            for(int p = i; p < j; p++){
                if(boxes[p] == boxes[j]){
                    dp[i][j][k] = Math.max(dp[i][j][k], dfs(boxes, i, p, k + 1) + dfs(boxes, p + 1, j - 1, 0));
                }
            }
            return dp[i][j][k];
        }
        }
      

Reference

  1. 花花酱 LeetCode 546. Remove Boxes