- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Binary Subarrays With Sum in C++
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
#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
Advertisements