You are given an array ‘ARR’ of integer elements. You have to find the maximum sum of the subset of elements in the array such that no two elements in the subset are adjacent to each other.
Note: A subset of array ‘ARR’ is a tuple that can be obtained from ‘ARR’ by removing some (possibly all) elements from it, without changing the order of the remaining elements.
EXAMPLE:Input:
'N' = 5
‘ARR’ = [1, 2, 3, 4, 5]
Output: 9
The optimal subset would be [1, 3, 5], in which no two elements are adjacent to each other and the sum of the subset is 9. We cannot make the sum greater than 9.
The first line will contain the integer 'T', the number of test cases. For each test case
In the first line of each test case, an integer ‘N’ denotes the length of the array ‘ARR’.
The second line of each test case contains ‘N’ integers denoting the elements of array ‘ARR’.
Output format :
For each test case, print the maximum sum of the subset.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= 'T' <= 10
4 <= 'N' <= 10^5
1 <= ‘ARR[i]’ <= 10^5
Time Limit: 1 sec
2
1
10
4
2 1 1 2
10
4
In the first test case, the optimal subset is [10] with the sum ‘10’.
Hence the answer is ‘10’.
In the second test case, the optimal subset is [2, 2] with no adjacent elements and sum ‘4’.
Hence the answer is ‘4’.
2
4
4 3 7 6
4
3 7 5 1
11
8
Try Dynamic programming.
Approach:
Algorithm :
O(N), Where ‘N’ is the length of the array ‘ARR’.
Calculating the answer for ‘N’ states takes ~N time, the time complexity will be O(N).
O(N), Where ‘N’ is the length of the array ‘ARR’.
Creating the ‘DP’ array takes ~N space, Hence the space complexity will be O(N).