Remove Boxes

This page explains Java solution to problem Remove Boxes using Dynamic Programming.

Problem Statement

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

Solution

If you have any suggestions in below code, please create a pull request by clicking here.

package com.vc.hard;

class RemoveBoxes {
    public int removeBoxes(int[] boxes) {
        if(boxes == null || boxes.length == 0) return 0;
        int n = boxes.length;
        int[][][] dp = new int[n][n][n];
        return helper(boxes, 0, n - 1, 0, dp);
    }

    private int helper(int[] boxes, int left, int right, int same, int[][][] dp) {
        if(left > right) return 0;

        if(dp[left][right][same] != 0) return dp[left][right][same];

        int res = (same + 1) * (same + 1) + helper(boxes, left + 1, right, 0, dp);

        for(int middle = left + 1; middle <= right; middle++) {
            if(boxes[left] == boxes[middle]) {
                res = Math.max(res, helper(boxes, left + 1, middle - 1, 0, dp) + helper(boxes, middle, right, same + 1, dp));
            }
        }

        dp[left][right][same] = res;
        return res;
    }
}

Time Complexity

O(N4) Where
N is total number of elements in an input array.

Space Complexity

O(N3) Where
N is total number of elements in an input array