Gary is bored and wants to play an interesting but tough game. So he figured out a new board game called "destroy the neighbours". In this game, there are N integers on a board. In one move, he can pick any integer x from the board, and then all the integers with value x + 1 or x - 1 get destroyed. This move will give him x points.
He plays the game until the board becomes empty. But as he wants to show this game to his friend Steven, he wants to learn techniques to maximize the points to show off. Can you help Gary in finding out the maximum points he receives from the game?
The first line of input contains an integer ‘T’, denoting the number of test cases. Then each test case follows.
The first line of each test case contains the Integer ‘N’ denoting the number of elements in the array.
The second and the last line of each test case contains ‘N’ single space-separated integers representing the elements of the array.
Output Format:
For each test case, print a single integer ‘X’, denoting the maximum points he receives from the game.
Output of each test case will be printed on 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 <= 5
1 <= N <= 10 ^ 5
1 <= arr[i] <= 10 ^ 6
Time Limit: 1 sec.
2
5
1 2 3 4 5
6
1 3 3 2 5 4
9
12
For test case 1, The maximum number of points he can receive is 9 by selecting 1, 3 and 5
For test case 2, The maximum number of points he can receive is 12 by selecting 1, 3, 3 and 5.
2
9
3 9 3 8 8 7 9 5 10
9
5 1 6 10 1 6 3 7 5
37
32
Can you solve the question using the frequency of elements?
The idea is to store the frequency of each number from 0 to maximum element M.
Now for each element from 0 to M, there are two choices: either we pick it or skip it.
So, we can break the problem into subproblems using the following observation:
Let P(i, d) be the maximum point we can collect by picking elements from ‘i’ to M where 0 <= d <=1, if d is 0 it means we have picked the previous( i - 1 th) element else not.
Then,
P(i, 0) = max( P(i + 1, 1) + frequency[i] * i, P(i + 1, 0))
P(i, 1) = P(i + 1, 0)
This gives the optimal substructure.
The steps are as follows:
O(2 ^ M) where ‘M’ is the maximum element in the array.
For each element from 1 to ‘M’ we are finding the maximum out of two choices, either we pick it or skip it. Hence time complexity is O(2 ^ M).
O(M) where ‘M’ is the maximum element in the array.
We are using the ‘frequency’ array of size ‘M’ and there can be a maximum ‘M’ call stack. Hence the space complexity is O(2 * M) = O(M).