leetcode 930 - Binary Subarrays With Sum

https://leetcode.com/problems/binary-subarrays-with-sum/

In an array A of 0s and 1s, how many non-empty subarrays have sum S?

Example 1:

Input: A = [1,0,1,0,1], S = 2
Output: 4
Explanation:
The 4 subarrays are bolded below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]

Note:

A.length <= 30000
0 <= S <= A.length
A[i] is either 0 or 1.

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
class Solution {
public:
int numSubarraysWithSum(vector<int>& A, int S) {
int size = A.size();
int i = 0;
int k;
int sum = 0;
int total = 0;

for (int j = 0; j < size; j++) {
sum += A[j];

while (sum > S && i < j) {
sum -= A[i++];
k = i;
}

if (sum == S) {
k = i;
while (k < j && A[k] != 1)
k++;
total += k - i + 1;
}
}

return total;
}
};