


If you are given ARR = [2, 5, 1, 2, 7, 3, 0] and K = 2, the output is 17.
We can choose non-overlapping subarrays [2, 5] and [7, 3] to get a total sum of 17 (i.e. 2 + 5 + 7 + 3) which is the maximum possible sum.
The first line of input contains an integer 'T' representing the number of test cases or queries to be processed. Then the test case follows.
The first line of each test case contains two single space-separated integers ‘N’ and ‘K’, respectively. ‘N’ represents the size of the array/list.
The second line of each test case contains N single space-separated integers representing the array/list elements.
For each test case, print a single line containing a single integer representing the total maximum possible sum.
The output of each test case will be printed in a separate line.
You do not need to print anything, it has already been taken care of. Just implement the function.
1 <= T <= 10 ^ 2
2 <= N <= 5 * 10 ^ 3
1 <= K <= N / 2
-10 ^ 5 <= ARR[i] <= 10 ^ 5
Where ‘N’ is the number of elements in the array/list ARR.
ARR[i] represents the ith element of ARR.
Time Limit: 1 sec.
The problem boils down to finding the sum of all pairs of non-overlapping subarrays of size K. We can naively find all non-overlapping subarray pairs by two nested loops, with the outer loop (loop variable i) running from 0 to N - 2 * K and inner loop (loop variable j) running from i + K to N - K. The range of loops is taken in such a way that it will prevent any overlapping of subarrays.
Following is the algorithm for this approach:
We store the prefix sum (the sum of all elements from first until the last element) in the PREFIXSUM array to calculate the sum of subarrays of size K easily.
We maintain a DP array where DP[i] denotes the subarray sum that is maximum among all possible subarrays of size K till index i.
For the subarray of size K ending at index i (i.e. [i - K + 1: i]), we need to find the maximum subarray sum of size K that ends before this subarray (i.e. ending on or before i - K) which is given by DP[i - K].
Here is the complete algorithm: