

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.
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.
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.
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:
The idea is to store the frequency of each number from 0 to maximum element range 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 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.
If you observe, there are repetitive subproblems. We can avoid the recomputation of those repetitive subproblems by memoization.
The steps are as follows:
Before coming to this question, what if array elements contain all the numbers from 1 to ‘N’. like 1, 2, 3, 4, 5, 6. Then you can clearly say that , if I select ith element then i will not select ‘i’ - 1 th element and if I don’t select ith element then to maximize points we must select i -1 th element. So, for every element there are two states either it is selected or not. Now this problem can give the sense of using dp ..right?
Similarly we can generalize this for duplicate elements like 1, 1, 2, 3, 3, 4, 4, 5.
We can keep the frequency of each element. The elements which are not present in the array then their frequency is 0.
The steps are as follows: