Smallest subarray of size greater than K with sum greater than a given value

• Difficulty Level : Hard
• Last Updated : 03 May, 2021

Given an array, arr[] of size N, two positive integers K and S, the task is to find the length of the smallest subarray of size greater than K, whose sum is greater than S.

Examples:

Input: arr[] = {1, 2, 3, 4, 5}, K = 1, S = 8
Output: 2
Explanation:
Smallest subarray with sum greater than S(=8) is {4, 5}
Therefore, the required output is 2.

Input: arr[] = {1, 3, 5, 1, 8, 2, 4}, K= 2, S= 13
Output: 3

Approach: The problem can be solved using Sliding Window Technique. Follow the steps below to solve the problem:

1. Initialize two variables say, i = 0 and j = 0 both pointing to the start of array i.e index 0.
2. Initialize a variable sum to store the sum of the subArray currently being processed.
3. Traverse the array, arr[] and by incrementing j and adding arr[j]
4. Take our the window length or the length of the current subArray which is given by j-i+1 (+1 because the indexes start from zero) .
5. Firstly, check if the size of the current subArray i.e winLen  here is greater than K. if this is not the case increment the j value and continue the loop.
6. Else , we get that the size of the current subArray is greater than K, now we have to check if we meet the second condition i.e sum of the current Subarray is greater than S.
7. If this is the case, we update minLength variable which stores the minimum length of the subArray satisfying the above conditions.
8. At this time , we check if the size of the subArray can be reduced (by incrementing i such that it still is greater than K and sum is also greater than S. We constantly remove the ith element of the array from the sum to reduce the subArray size in the While loop and then increment j such that we move to the next element in the array .the
9. Finally, print the minimum length of required subarray obtained that satisfies the conditions.

Below is the implementation of the above approach:

C++

 // C++ program to implement// the above approach #include using namespace std; // Function to find the length of the// smallest subarray of size > K with// sum greater than Sint smallestSubarray(int K, int S,                     int arr[], int N){    // Store the first index of    // the current subarray    int start = 0;     // Store the last index of    // the the current subarray    int end = 0;     // Store the sum of the    // current subarray    int currSum = arr;     // Store the length of    // the smallest subarray    int res = INT_MAX;     while (end < N - 1) {         // If sum of the current subarray <= S        // or length of current subarray <= K        if (currSum <= S            || (end - start + 1) <= K) {            // Increase the subarray            // sum and size            currSum += arr[++end];        }         // Otherwise        else {             // Update to store the minimum            // size of subarray obtained            res = min(res, end - start + 1);             // Decrement current subarray            // size by removing first element            currSum -= arr[start++];        }    }     // Check if it is possible to reduce    // the length of the current window    while (start < N) {        if (currSum > S            && (end - start + 1) > K)            res = min(res, (end - start + 1));         currSum -= arr[start++];    }    return res;} // Driver Codeint main(){    int arr[] = { 1, 2, 3, 4, 5 };    int K = 1, S = 8;    int N = sizeof(arr) / sizeof(arr);    cout << smallestSubarray(K, S, arr, N);}

Java

 // Java program to implement// the above approachimport java.io.*; class GFG{ // Function to find the length of the// smallest subarray of size > K with// sum greater than Spublic static int smallestSubarray(int k, int s,                                   int[] array, int N){             int i=0;        int j=0;        int minLen = Integer.MAX_VALUE;        int sum = 0;         while(j < N)        {            sum += array[j];            int winLen = j-i+1;            if(winLen <= k)                j++;            else{                if(sum > s)                {                    minLen = Math.min(minLen,winLen);                    while(sum > s)                    {                        sum -= array[i];                        i++;                    }                    j++;                }            }        }        return minLen;} // Driver Codepublic static void main(String[] args){    int[] arr = { 1, 2, 3, 4, 5 };    int K = 1, S = 8;    int N = arr.length;         System.out.print(smallestSubarray(K, S, arr, N));}} // This code is contributed by akhilsaini

Python3

 # Python3 program to implement# the above approachimport sys # Function to find the length of the# smallest subarray of size > K with# sum greater than Sdef smallestSubarray(K, S, arr, N):     # Store the first index of  # the current subarray  start = 0   # Store the last index of  # the the current subarray  end = 0   # Store the sum of the  # current subarray  currSum = arr   # Store the length of  # the smallest subarray  res = sys.maxsize   while end < N - 1:       # If sum of the current subarray <= S      # or length of current subarray <= K      if ((currSum <= S) or         ((end - start + 1) <= K)):                     # Increase the subarray          # sum and size          end = end + 1;          currSum += arr[end]       # Otherwise      else:           # Update to store the minimum          # size of subarray obtained          res = min(res, end - start + 1)           # Decrement current subarray          # size by removing first element          currSum -= arr[start]          start = start + 1   # Check if it is possible to reduce  # the length of the current window  while start < N:      if ((currSum > S) and         ((end - start + 1) > K)):          res = min(res, (end - start + 1))             currSum -= arr[start]      start = start + 1   return res; # Driver Codeif __name__ == "__main__":       arr = [ 1, 2, 3, 4, 5 ]  K = 1  S = 8  N = len(arr)     print(smallestSubarray(K, S, arr, N)) # This code is contributed by akhilsaini

C#

 // C# program to implement// the above approachusing System; class GFG{ // Function to find the length of the// smallest subarray of size > K with// sum greater than Sstatic int smallestSubarray(int K, int S,                            int[] arr, int N){         // Store the first index of    // the current subarray    int start = 0;     // Store the last index of    // the the current subarray    int end = 0;     // Store the sum of the    // current subarray    int currSum = arr;     // Store the length of    // the smallest subarray    int res = int.MaxValue;     while (end < N - 1)    {                 // If sum of the current subarray <= S        // or length of current subarray <= K        if (currSum <= S ||           (end - start + 1) <= K)        {                         // Increase the subarray            // sum and size            currSum += arr[++end];        }         // Otherwise        else        {             // Update to store the minimum            // size of subarray obtained            res = Math.Min(res, end - start + 1);             // Decrement current subarray            // size by removing first element            currSum -= arr[start++];        }    }     // Check if it is possible to reduce    // the length of the current window    while (start < N)    {        if (currSum > S && (end - start + 1) > K)            res = Math.Min(res, (end - start + 1));         currSum -= arr[start++];    }    return res;} // Driver Codestatic public void Main(){    int[] arr = { 1, 2, 3, 4, 5 };    int K = 1, S = 8;    int N = arr.Length;         Console.Write(smallestSubarray(K, S, arr, N));}} // This code is contributed by akhilsaini

Javascript



Output:
2

Time Complexity: O(N)
Auxiliary Space:O(1)

My Personal Notes arrow_drop_up