![]() |
VOOZH | about |
Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.
Note: If K is less than the minimum element, then return INT_MIN.
Examples:
Input: arr[] = {-1, 2, 2}, K = 4
Output: 3
Explanation:
The subarray with maximum sum which is less than 4 is {-1, 2, 2}.
The subarray {2, 2} has maximum sum = 4, but it is not less than 4.Input: arr[] = {5, -2, 6, 3, -5}, K =15
Output: 12
Explanation:
The subarray with maximum sum which is less than 15 is {5, -2, 6, 3}.
Efficient Approach: Sum of subarray [i, j] is given by cumulative sum till j - cumulative sum till i of the array. Now the problem reduces to finding two indexes i and j, such that i < j and cum[j] - cum[i] are as close to K but lesser than it.
To solve this, iterate the array from left to right. Put the cumulative sum of i values that you have encountered till now into a set. When you are processing cum[j] what you need to retrieve from the set is the smallest number in the set which is bigger than or equal to cum[j] - K. This can be done in O(logN) using upper_bound on the set.
Below is the implementation of the above approach:
12
Time Complexity: O(N*Log(N)), where N represents the size of the given array.
Auxiliary Space: O(N), where N represents the size of the given array.
Similar article:Maximum sum subarray having sum less than or equal to given sum using Sliding Window