![]() |
VOOZH | about |
Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous subarray with length between A and B.
Examples:
Input: N = 8, A = 1, B = 2, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}
Output: 8
Explanation: The subarray with maximum sum is {5, 3}, the length between 1 and 2, and the sum is 8.Input: N = 8, A = 1, B = 1, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}
Output: 5
Explanation: The subarray with maximum sum is {5} with length between 1 and 1, and the sum is 5.
Approach: To solve the problem, follow the below idea:
The idea is to calculate the prefix sum of the given array and calculate the maximum subarray sum, with length being between a and b for each subarray starting at index i. To calculate the maximum subarray sum starting at index i, will be: max(prefixSum[i+a-1] ....... prefixSum[i+b-1]) - prefixSum[i-1], i.e., we need to pick the maximum value from the prefixSum array from the index (i+a-1) to (i+b-1) and subtract prefixSum[i-1] from it, this gives the maximum subarray starting from index i and the length being between a and b. The final answer will be the maximum value among all possible starting index i from 1 to (n-a).
To find the maximum value in the range for each starting index i, it can be observed that window size will be constant which is (b-a+1). So, we can use a deque to maintain the maximum value for each window. You can refer to this article for more details: Sliding Window Maximum (Maximum of all subarrays of size K)
Step-by-step algorithm:
Below is the implementation of above approach:
8
Time Complexity: O(N), where N is the size of input array arr[].
Auxiliary Space: O(N)