Maximum sum subarray having sum less than or equal to given sum using Set

Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with sum less than K.

Note: If K is less than 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 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 cum[j] – K. This can be done in O(logN) using upper_bound on the set.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find maximum sum
// subarray less than K
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to maximum required sum < K
int maxSubarraySum(int arr[], int N, int K)
{
  
    // Hash to lookup for value (cum_sum - K)
    set<int> cum_set;
    cum_set.insert(0);
  
    int max_sum = INT_MIN, cSum = 0;
  
    for (int i = 0; i < N; i++) {
  
        // getting cummulative sum from [0 to i]
        cSum += arr[i];
  
        // lookup for upperbound
        // of (cSum-K) in hash
        set<int>::iterator sit
            = cum_set.upper_bound(cSum - K);
  
        // check if upper_bound
        // of (cSum-K) exists
        // then update max sum
        if (sit != cum_set.end())
  
            max_sum = max(max_sum,
                          cSum - *sit);
  
        // insert cummulative value in hash
        cum_set.insert(cSum);
    }
  
    // return maximum sum
    // lesser than K
    return max_sum;
}
  
// Driver code
int main()
{
  
    // initialise the array
    int arr[] = { 5, -2, 6, 3, -5 };
  
    // initialise the vaue of K
    int K = 15;
  
    // size of array
    int N = sizeof(arr) / sizeof(arr[0]);
  
    cout << maxSubarraySum(arr, N, K);
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# python3 program to find maximum sum
# subarray less than K
import sys,bisect
  
# Function to maximum required sum < K
def maxSubarraySum(arr,N,K):
    # Hash to lookup for value (cum_sum - K)
    cum_set = set()
    cum_set.add(0)
  
    max_sum = 12
    cSum = 0
  
    for i in range(N):
        # getting cummulative sum from [0 to i]
        cSum += arr[i]
  
        # check if upper_bound
        # of (cSum-K) exists
        # then update max sum
        x = 5
        if x in cum_set:
            max_sum = max(max_sum,cSum - x)
  
        # insert cummulative value in hash
        cum_set.add(cSum)
  
    # return maximum sum
    # lesser than K
    return max_sum
  
# Driver code
if __name__ == '__main__':
    # initialise the array
    arr = [5, -2, 6, 3, -5]
  
    # initialise the vaue of K
    K = 15
  
    # size of array
    N = len(arr)
  
    print(maxSubarraySum(arr, N, K))
  
# This code is contributed by Surendra_Gangwar

chevron_right


Output:

12

Time Complexity: O(N*Log(N))

Similar article: Maximum sum subarray having sum less than or equal to given sum using Sliding Window

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : SURENDRA_GANGWAR