# Remove Boxes in C++

Suppose we have several boxes with different colors These colors are represented by different positive numbers. We can experience several rounds to remove boxes until there is no box left. In each round we can choose some continuous boxes with the same color (composed of k boxes, k >= 1), and remove them and get k*k points. So if the input is like − [1,3,2,2,2,4,4,3,1], then the output will be 21.

Find the maximum points you can get.

To solve this, we will follow these steps −

• Define a function solve(), this will take an array boxes, i, j, k, one 3D array dp,
• if i > j, then −
• return 0
• if dp[i, j, k] is not equal to -1, then −
• return dp[i, j, k]
• ret := -inf
• for checking condition i + 1 <= j and boxes[i + 1] is same as boxes[i], update (increase i by 1), (increase k by 1), do nothing −
• ret := maximum of ret and (k + 1) * (k + 1) + call the function solve(boxes, i + 1, j, 0, dp)
• for initialize x := i + 1, when x <= j, update (increase x by 1), do −
• if boxes[x] is same as boxes[i], then −
• ret := maximum of ret and solve((boxes, i + 1, x - 1, 0, dp) + solve(boxes, x, j, k + 1, dp))
• return dp[i, j, k] = ret
• From the main method, do the following
• n := size of boxes
• Define one 3D array dp of order (n + 1) x (n + 1) x (n + 1), fill this with -1
• return solve(boxes, 0, n - 1, 0, dp)

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(vector <int>& boxes, int i, int j, int k, vector < vector < vector <int > > >& dp){
if(i > j) return 0;
if(dp[i][j][k] != -1) return dp[i][j][k];
int ret = INT_MIN;
for(; i + 1 <= j && boxes[i + 1] == boxes[i]; i++, k++);
ret = max(ret, (k + 1) * (k + 1) + solve(boxes, i + 1, j, 0, dp));
for(int x = i + 1; x <= j; x++){
if(boxes[x] == boxes[i]){
ret = max(ret, solve(boxes, i + 1, x - 1, 0, dp) + solve(boxes, x, j, k + 1,          dp));
}
}
return dp[i][j][k] = ret;
}
int removeBoxes(vector<int>& boxes) {
int n = boxes.size();
vector < vector < vector <int > > > dp(n + 1, vector < vector <int> > (n + 1, vector <int>(n + 1, -1)));
return solve(boxes, 0, n - 1, 0, dp);
}
};
main(){
Solution ob;
vector<int> v = {1,3,2,2,2,4,4,3,1};
cout << (ob.removeBoxes(v));
}

## Input

{1,3,2,2,2,4,4,3,1}

## Output

21