Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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

 

Naive Approach

The idea is to find all subarrays and in that choose those subarrays whose sum is greater than S and whose length is greater than K. After that from those subarrays, choose that subarray whose length is minimum. Then print the length of that subarray.

Steps that were to follow the above approach:

  • Make a variable “ans” and initialize it with the maximum value
  • After that run two nested loops to find all subarrays
  • While finding all subarray calculate their size and sum of all elements of that subarray
  • If the sum of all elements is greater than S and its size is greater than K, then update answer with minimum of answer and length of the subarray

Below is the code to implement 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)
{
   //To store answer
   int ans=INT_MAX;
   
  //Traverse the array
   for(int i=0;i<N;i++){
       //To store size of subarray
       int size=0;
       //To store sum of all elements of subarray
       int sum=0;
       for(int j=i;j<N;j++){
           size++;
           sum+=arr[j];
          
           //when size of subarray is greater than k and sum of all element
           //is greater than S then if size is less than previously stored answer
           //then update answer with size
           if(size>K && sum>S){
               if(size<ans){ans=size;}
           }
       }
   }
   return ans;
}
 
// 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




import java.util.*;
 
public class Main
{
 
  // 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)
  {
 
    // To store answer
    int ans = Integer.MAX_VALUE;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
      // To store size of subarray
      int size = 0;
      // To store sum of all elements of subarray
      int sum = 0;
      for (int j = i; j < N; j++) {
        size++;
        sum += arr[j];
 
        // when size of subarray is greater than k and sum of all element
        // is greater than S then if size is less than previously stored answer
        // then update answer with size
        if (size > K && sum > S) {
          if (size < ans) {
            ans = size;
          }
        }
      }
    }
    return ans;
  }
 
  // 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.println(smallestSubarray(K, S, arr, N));
  }
}


Python3




# Function to find the length of the smallest subarray of
# size > K with sum greater than S
def smallestSubarray(K, S, arr, N):
   
    # To store answer
    ans = float('inf')
 
    # Traverse the array
    for i in range(N):
       
        # To store size of subarray
        size = 0
         
        # To store sum of all elements of subarray
        sum = 0
        for j in range(i, N):
            size += 1
            sum += arr[j]
 
            # when size of subarray is greater than k and sum of all element
            # is greater than S then if size is less than previously stored answer
            # then update answer with size
            if size > K and sum > S:
                if size < ans:
                    ans = size
 
    return ans
 
# Driver Code
arr = [1, 2, 3, 4, 5]
K = 1
S = 8
N = len(arr)
print(smallestSubarray(K, S, arr, N))


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)
    {
        // To store the answer
        int ans = int.MaxValue;
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
            // To store the size of the subarray
            int size = 0;
            // To store the sum of all elements of the
            // subarray
            int sum = 0;
            for (int j = i; j < N; j++) {
                size++;
                sum += arr[j];
 
                // When the size of the subarray is greater
                // than K and the sum of all elements is
                // greater than S, then if the size is less
                // than the previously stored answer update
                // the answer with the size
                if (size > K && sum > S) {
                    if (size < ans) {
                        ans = size;
                    }
                }
            }
        }
        return ans;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5 };
        int K = 1, S = 8;
        int N = arr.Length;
        Console.WriteLine(SmallestSubarray(K, S, arr, N));
    }
}
 
// This code is contributed by shivamgupta0987654321


Javascript




// Function to find the length of the smallest subarray of
// size > K with sum greater than S
function smallestSubarray(K, S, arr, N) {
  // To store answer
  let ans = Infinity;
 
  // Traverse the array
  for (let i = 0; i < N; i++) {
    // To store size of subarray
    let size = 0;
 
    // To store sum of all elements of subarray
    let sum = 0;
    for (let j = i; j < N; j++) {
      size += 1;
      sum += arr[j];
 
      // when size of subarray is greater than k and sum of all element
      // is greater than S then if size is less than previously stored answer
      // then update answer with size
      if (size > K && sum > S) {
        if (size < ans) {
          ans = size;
        }
      }
    }
  }
  return ans;
}
 
// Driver Code
let arr = [1, 2, 3, 4, 5];
let K = 1;
let S = 8;
let N = arr.length;
console.log(smallestSubarray(K, S, arr, N));


Output-

2

Time Complexity: O(N2), because of two nested for loops
Auxiliary Space:O(1) , because no extra space has been used

 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 <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 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];
        }
        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);
}
 
// This code is contributed by Sania Kumari Gupta


C




// C program to implement the above approach
#include <limits.h>
#include <stdio.h>
 
// Find minimum between two numbers.
int min(int num1, int num2)
{
    return (num1 > num2) ? num2 : num1;
}
 
// 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 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];
        }
        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]);
    printf("%d", smallestSubarray(K, S, arr, N));
}
 
// This code is contributed by Sania Kumari Gupta


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[] 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 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 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 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 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) 



Last Updated : 19 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads