Skip to content
Related Articles

Related Articles

Smallest subarray of size greater than K with sum greater than a given value
  • Difficulty Level : Medium
  • Last Updated : 19 Mar, 2021
GeeksforGeeks - Summer Carnival Banner

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, start = 0 and end = 0 to store the first and last index of current subarray respectively.
  2. Traverse the array, arr[] and by incrementing end and adding arr[end] to the sum of the current subarray.
  3. If sum of all the elements of the current subarray is less than or equal to S or the length of the current subarray is less than or equal to K, then increment the length of current subarray(end++).
  4. Otherwise, decrement the length of current subarray by removing the first element of the current subarray (start -= 1). Update the minimum length of required subarray found till now by comparing it with the length of the current subarray.
  5. 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 <bits/stdc++.h>
using namespace std;
 
// Function to find the length of the
// smallest subarray of size > K with
// sum greater than S
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[0];
 
    // 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 Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int K = 1, S = 8;
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << smallestSubarray(K, S, arr, N);
}

Java




// Java program to implement
// the above approach
import java.io.*;
 
class GFG{
 
// Function to find the length of the
// smallest subarray of size > K with
// sum greater than S
public static 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[0];
 
    // Store the length of
    // the smallest subarray
    int res = Integer.MAX_VALUE;
 
    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 Code
public 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 approach
import sys
 
# Function to find the length of the
# smallest subarray of size > K with
# sum greater than S
def 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[0]
 
  # 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 Code
if __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 approach
using System;
 
class GFG{
 
// Function to find the length of the
// smallest subarray of size > K with
// sum greater than S
static 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[0];
 
    // 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 Code
static 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




<script>
// JavaScript program to implement
// the above approach
 
// Function to find the length of the
// smallest subarray of size > K with
// sum greater than S
function smallestSubarray(K, S, arr, N)
{
 
    // Store the first index of
    // the current subarray
    let start = 0;
 
    // Store the last index of
    // the the current subarray
    let end = 0;
 
    // Store the sum of the
    // current subarray
    let currSum = arr[0];
 
    // Store the length of
    // the smallest subarray
    let res = Number.MAX_SAFE_INTEGER;
    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 Code
    let arr = [ 1, 2, 3, 4, 5 ];
    let K = 1, S = 8;
    let N = arr.length;
    document.write(smallestSubarray(K, S, arr, N));
 
// This code is contributed by Surbhi tyagi.
</script>

 
 

Output: 
2

 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :