forked from Rahul-skush/leetcode-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path930. Binary Subarrays With Sum
47 lines (45 loc) · 1.01 KB
/
930. Binary Subarrays With Sum
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:
int numSubarraysWithSum(vector<int>& A, int S) {
int n = A.size();
if(S==0) return helper(A, n);
int lo=0, hi=0, prev =-1, count=0, sum =0;
while(hi<n && A[hi]!=1)
lo++, hi++;
while(hi<n)
{
if(sum +A[hi]==S)
{
count+=lo -prev;
sum+=A[hi];
hi++;
}
else
if(sum+A[hi]>S)
{
sum-=A[lo];
prev =lo;
lo++;
while(A[lo]!=1)lo++;
}
else
{
sum += A[hi];
hi++;
}
}
return count;
}
int helper(vector<int> A,int n)
{
int count =0, ans=0;
for(int i=0;i<n;i++)
{
if(A[i]==0)
count++, ans+=count;
else
count=0;
}
return ans;
}
};