-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySubarraysWithSum.cpp
More file actions
38 lines (34 loc) · 971 Bytes
/
BinarySubarraysWithSum.cpp
File metadata and controls
38 lines (34 loc) · 971 Bytes
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
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numSubarraysWithSum(vector<int>& nums, int goal) {
int n = nums.size(), sum = 0, j = 0, count = 0;
for (int i = 0; i < n; i++) {
sum += nums[i];
while (sum > goal) {
sum -= nums[j++];
}
if (sum == goal && j <= i) {
count++;
int k = j;
while (k < i && !nums[k]) k++, count++;
}
}
return count;
}
int numSubarraysWithSum(vector<int>& nums, int goal) {
int n = nums.size(), ans = 0;
vector<int> sum(n + 1);
sum[0] = 0;
for (int i = 0; i < n; i++) sum[i + 1] = sum[i] + nums[i];
unordered_map<int, int> seen;
for (int x : sum) {
ans += seen[x];
seen[x + goal]++;
}
return ans;
}
};
int main() {
}