Skip to content

Commit

Permalink
Create 930.Binary-Subarrays-With-Sum_v2.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored May 21, 2022
1 parent 7545bae commit 3a30051
Showing 1 changed file with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution {
public:
int numSubarraysWithSum(vector<int>& A, int S)
{
int n = A.size();
vector<int>postZeros(n);
int count = 0;
for (int i=n-1; i>=0; i--)
{
postZeros[i] = count;
if (A[i]==0)
count++;
else
count = 0;
}

int j = 0, sum = 0;
int ret = 0;
for (int i=0; i<n; i++)
{
while (j<=i || (j<n && sum < S))
{
sum += A[j];
j++;
}

if (sum==S)
ret += postZeros[j-1]+1;
sum -= A[i];
}

return ret;
}
};

0 comments on commit 3a30051

Please sign in to comment.