Maximum sum two non-overlapping subarrays of given size
You are given an array/list ARR of integers and a positive integer ‘K’. Your task is to find two non-overlapping subarrays (contiguous) each of length ‘K’ such that the total sum of these subarrays is maximum.
For Example:
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.
You can assume that the array will always contain at least two non-overlapping subarrays with size ‘K’. So, the answer will always exist.
Input Format:
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.
Output Format :
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.
Note:
You do not need to print anything, it has already been taken care of. Just implement the function.
Constraints:
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.
CodingNinjas
author
2y
Can be done by first calculating the max sum and then the min sum and calculating the difference at each position.
CodingNinjas
author
2y
Brute Force
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 loo...read more
CodingNinjas
author
2y
Dynamic Programming
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...read more
Add answer anonymously...
Top Expedia Group Software Developer interview questions & answers
Popular interview questions of Software Developer
>
Expedia Group Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app