You are given several boxes with different colours represented by different positive numbers. For moving the boxes you can remove them in multiple iterations until there are no boxes left. Now, every 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 for removing them.
Your task for the problem is to find and return the maximum points you can get by removing those boxes.
For Example: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] (Remove 3 boxes with number 2, 3*3=9 points)
----> [1, 3, 3, 3, 1] (Remove one box with number 4, 1*1=1 points)
----> [1, 1] (Remove 3 boxes with number 3, 3*3=9 points)
----> [] (2*2=4 points)
The first line of input contains a single integer ‘T’ denoting the number of test cases that would be there.
The first line of each test case contains a single integer ‘N’ denoting the number of boxes that would be given.
And the next line contains ‘N’ space-separated integers which are the colors of the boxes represented as integers.
Output Format :
For each test case, print the maximum points that could be collected by removing the boxes of the same color from the list.
The output of each test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= boxes.length <= 50
1 <= boxes[i] <= 100
Time Limit: 1 sec
2
7
1 2 3 3 2 1 1
9
1 3 2 2 2 3 4 3 1
17
23
Test Case 1:
[1, 2, 3, 3, 2, 1, 1]
Remove 33 ----> [1, 2, 2, 1, 1] (2 * 2 = 4 points)
Remove 22 ----> [1, 1, 1] (2 * 2 = 4 points)
Remove 111 ----> [] (3 * 3 = 9 points)
Thus, total points are 17.
Test Case 2:
[1, 3, 2, 2, 2, 3, 4, 3, 1]
Remove 222 ----> [1, 3, 3, 4, 3, 1] (3 * 3 = 9 points)
Remove 4 ----> [1, 3, 3, 3, 1] (1 * 1 = 1 points)
Remove 333 ----> [1, 1] (3 * 3 = 9 points)
Remove 22 ----> [] (2 * 2 = 4 points)
Thus, total points are 23.
1
3
1 1 1
9
Test Case 1:
[1, 1, 1]
Remove 111 ----> [] (3 * 3 = 9 points)
Thus, total points are 9.
Try to recursively maximize the points by checking which box removals are the most profitable out of all the different possible removals.
Approach: The idea here is to store the repeated set of sub solutions for the problem. Then return the solution you already have calculated the value for recursively building the lookup table.
The algorithm will be:
O(2 ^ N), where ‘N’ denotes the number of boxes given in the problem.
Since we are splitting the problem into subproblems of smaller size in each iteration recursively therefore, the time complexity will be O(2 ^ N).
O(N), where ‘N’ denotes the number of boxes given in the problem.
Since we are making as many recursive calls as the height of the tree and the tree is at most n height. That is why the space complexity is O(N)