Maximum subarray size, such that all subarrays of that size have sum less than k in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find maximum subarray size, such that all subarrays of that size have sum less than k.

For this we will be provided with an array of size N and an integer k. Our task is to find the length of subarray such that all the sub-arrays of that length in the given array sum to be less than or equal to k.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
//finding maximum length subarray
int bsearch(int prefixsum[], int n, int k) {
   int ans = -1;
   //performing binary search
   int left = 1, right = n;
   while (left <= right) {
      int mid = (left + right) / 2;
      int i;
      for (i = mid; i <= n; i++) {
         if (prefixsum[i] - prefixsum[i - mid] > k)
         break;
      }
      if (i == n + 1) {
         left = mid + 1;
         ans = mid;
      }
      else right = mid - 1;
   }
   return ans;
}
//returning maximum subarray size
int maxSize(int arr[], int n, int k) {
   int prefixsum[n + 1];
   memset(prefixsum, 0, sizeof(prefixsum));
   for (int i = 0; i < n; i++)
   prefixsum[i + 1] = prefixsum[i] + arr[i];
   return bsearch(prefixsum, n, k);
}
int main() {
   int arr[] = {1, 2, 10, 4};
   int n = sizeof(arr) / sizeof(arr[0]);
   int k = 14;
   cout << maxSize(arr, n, k) << endl;
   return 0;
}

Output

2
raja
Published on 10-Jul-2020 14:03:26
Advertisements