In an array A
of 0
s and 1
s, 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 either0
or1
.
Solution: Prefix Sum
counts[s] := # of subarrays start from 0 that have sum of s
ans += counts[s – S] if s >= S
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua, 28 ms, 12.3 MB class Solution { public: int numSubarraysWithSum(vector<int>& A, int S) { const int n = A.size(); vector<int> counts(n + 1); counts[0] = 1; int ans = 0; int sum = 0; for (int a : A) { sum += a; if (sum >= S) ans += counts[sum - S]; ++counts[sum]; } return ans; } }; |