Binary Subarrays With Sum in C++

C++Server Side ProgrammingProgramming

Suppose an array A of 0s and 1s is given, we have to find how many non-empty subarrays have sum S? So if the input is like [1,0,1,0,1], and S = 2, then the result will be 4, as the subarrays are [1,0,1,0,1], [1,0,1,0,1], [1,0,1,0,1], [1,0,1,0,1].

To solve this, we will follow these steps −

  • Define a method called atMost(), this will take array A and integer x

  • if x < 0, then return 0, set j := 0 and set ret := 0

  • for i in range 0 to size of A

    • decrease x by A[i]

    • while x < 0

      • increase x by A[j], increase j by 1

    • ret := ret + i – j + 1

  • return ret

  • From the main method do the following −

  • ret := atMost(A, S) – atMost(A, S – 1)

  • return ret

Let us see the following implementation to get better understanding &mius;

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int atMost(vector <int>& A, int x){
      if(x < 0) return 0;
      int j = 0;
      int ret = 0;
      for(int i = 0; i < A.size(); i++){
         x -= A[i];
         while(x < 0){
            x += A[j];
            j++;
         }
         ret += i - j + 1;
      }
      return ret;
   }
   int numSubarraysWithSum(vector<int>& A, int S) {
      return atMost(A, S) - atMost(A, S - 1);
   }
};
main(){
   vector<int> v1 = {1,0,1,0,1};
   Solution ob;
   cout << (ob.numSubarraysWithSum(v1, 2));
}

Input

[1,0,1,0,1]

Output

4
raja
Published on 10-Apr-2020 10:09:59
Advertisements