Minimum Size Subarray Sum in C++


Suppose we have an array of n elements, and a positive integer s. We have to find the minimal length of a contiguous subarray, of which the sum is greater or equal to s. If there isn’t one,then return 0 instead. So if the array is like [2,3,1,2,3,4] and sum is 7, then the output will be 2. This is the subarray [4,3] has the minimum length for this case.

To solve this, we will follow these steps −

  • ans := 0, n := size of array A, j := 0 and sum := 0

  • for i in range 0 to n – 1

    • sum := sum + A[i]

    • while sum – A[i] >= K and j <= 1

      • sum := sum – A[j]

      • increase j by 1

    • if sum >= k, then

      • if ans = 0 or ans > (i – j + 1), then ans := (i – j + 1)

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int minSubArrayLen(int K, vector<int>& A) {
      int ans = 0;
      int n = A.size();
      int j = 0;
      int sum = 0;
      for(int i = 0; i < n; i++){
         sum += A[i];
         while(sum - A[j] >= K && j <= i){
            sum -= A[j];
            j++;
         }
         if(sum >= K){
            if(ans == 0 || ans > (i - j + 1)) ans = (i - j + 1);
         }
      }
   return ans;
   }
};
main(){
   vector<int> v = {2,3,1,2,4,3};
   Solution ob;
   cout << ((ob.minSubArrayLen(7,v)));
}

Input

7
[2,3,1,2,4,3]

Output

2

Updated on: 30-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements