Given an array ‘arr’ consisting of ‘N’ integer elements. You have to remove ‘K’ elements from the beginning or end of the array. Return the maximum possible sum of the remaining array elements.
Note: you can remove elements from both beginning and end, but a total of ‘K’ elements must be removed.
Example :
If N = 7 and K = 3, and the input array is:
{1, 2, 3, 4, 5, 6, 7}
After removing the first three elements, the resulting array now becomes {4, 5, 6, 7} and the sum of the remaining array is equal to 22.
Removing any other combination of three elements will always result in the remaining array sum less than 22.
The first line contains a single integer ‘T’ denoting the number of test cases. Then each test case follows.
The first line of each test case contains two integers ‘N’ and ‘K’, where N denotes the length of the given array and K denotes the number of elements to be removed.
The next line of each test case contains N integers denoting array elements ‘arr[i]’.
Output Format :
For each test case print a single integer denoting the maximum sum of the remaining array.
Output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N <= 10^4
0 <= K <= N
0 <= arr[i] <=10^6
Time limit: 1 sec
Sample Input 1 :
2
6 3
1 2 6 4 5 3
8 4
5 3 1 1 8 8 2 2
Sample Output 1 :
15
20
Explanation Of Sample Output 1 :
For test case 1 :
After removing two elements from the beginning and one element from the end, the original array now becomes {6, 4, 5}. The remaining elements of the array have a sum equal to 15.
For test case 2 :
After removing four elements from the beginning, the original array now becomes {8, 8, 2, 2}. The remaining elements of the array have a sum equal to 20.
Sample Input 2 :
2
5 5
4 5 7 2 3
5 0
1 2 3 4 5
Sample Output 2 :
0
15
Try all possible ways of removing the elements.
For each possible combination of removing elements from the array, calculate the sum of the remaining elements. Finally, return the maximum sum calculated over all the possible ways.
The steps are as follows:
O( K * N ), where ‘K’ is the number of elements to be removed and ‘N’ is the size of the input array.
Since we iterate over all possible K ways of removing elements, and then we calculate the sum of remaining elements ~N for each possible way, Hence the time complexity is O(K*N)
O(1)
Since constant space is used. Hence the space complexity is O(1).