-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path930.cpp
58 lines (57 loc) · 1.59 KB
/
930.cpp
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
48
49
50
51
52
53
54
55
56
57
58
__________________________________________________________________________________________________
sample 16 ms submission
class Solution {
public:
int numSubarraysWithSum(vector<int>& A, int S) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
vector <int> sum(A.size(),0);
vector<int> mp(A.size()+2,0);
sum[0]=A[0];
int no=0;
for(int i=0;i<A.size();i++)
{
if(i>=1)
sum[i]=sum[i-1]+A[i];
if(sum[i]-S>=0)
no+=mp[sum[i]-S];
mp[sum[i]]++;
}
no+=mp[S];
return no;
}
};
__________________________________________________________________________________________________
sample 10932 kb submission
static const auto _ = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 0;
}();
class Solution {
public:
int subarrays_with_sum_at_most(vector <int>& A, int S)
{
int ans = 0, L = 0, n = A.size(), sum = 0; // sum : A[L] + ... + A[i]
for(int i = 0; i < n; i++)
{
sum += A[i];
while(sum > S && L <= i)
{
sum -= A[L];
L++;
}
ans += i - L + 1;
}
return ans;
}
int numSubarraysWithSum(vector<int>& A, int S) {
int n = A.size();
int ans = subarrays_with_sum_at_most(A, S);
if(S > 0)
ans -= subarrays_with_sum_at_most(A, S - 1);
return ans;
}
};
__________________________________________________________________________________________________