Maximum sum subarray having sum less than or equal to given sums in C++


In this problem, we are given an array and a sum. Our task is to create a program that will find the maximum sum subarray having a sum less than or equal to given sums in c++.

We have to find the subarray of any length less than or equal to n whose sum is less than or equal to the given sum.

Let’s take an example to understand the problem,

Input − array = {3, 5, 1, 8, 2, 9}, sum = 25

Output − 25

Explanation − The subarrays with sum less than or equal to 25 are {5, 1, 8, 2, 9}

One simple method to find the maximum sum subarray is by iterating over the array and find the sum of all subarray and then finding the nearest or equal sum. But this method will have time complexity of O(n*n) as two loops are required.

A more efficient method to solve this problem is by using the sliding window method. In which we will check the current sum with the max sum and add or subtract elements to the window based on the comparison.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
int findMax(int a, int b){
   if(a>b)
      return a;
   return b;
}
int maxSumsubarray(int arr[], int n, int maxSum){
   int sum = arr[0], overallMax = 0, start = 0;
   for (int i = 1; i < n; i++) {
      if (sum <= maxSum)
      overallMax = findMax(overallMax, sum);
      while (sum + arr[i] > maxSum && start < i) {
         sum -= arr[start];
         start++;
      }
      sum += arr[i];
   }
   if (sum <= maxSum)
      overallMax = findMax(overallMax, sum);
   return overallMax;
}
int main(){
   int arr[] = {3, 1, 4, 7, 2, 9, 5};
   int n = sizeof(arr) / sizeof(arr[0]);
   int sum = 20;
   cout<<"The maximum sum of subarray with sum less than or equal to "<<sum<<" is "<<maxSumsubarray(arr, n, sum);
   return 0;
}

Output

The maximum sum of subarray with sum less than or equal to 20 is 18

Updated on: 03-Jun-2020

501 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements