-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathSubarray Sum Equals K.cpp
44 lines (33 loc) Β· 1.22 KB
/
Subarray Sum Equals K.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
class Solution {
public:
int subarraySum(vector<int>& arr, int k) {
int n = arr.size(); // take the size of the array
int prefix[n]; // make a prefix array to store prefix sum
prefix[0] = arr[0]; // for element at index at zero, it is same
// making our prefix array
for(int i = 1; i < n; i++)
{
prefix[i] = arr[i] + prefix[i - 1];
}
unordered_map<int,int> mp; // declare an unordered map
int ans = 0; // to store the number of our subarrays having sum as 'k'
for(int i = 0; i < n; i++) // traverse from the prefix array
{
if(prefix[i] == k) // if it already becomes equal to k, then increment ans
ans++;
// now, as we discussed find whether (prefix[i] - k) present in map or not
if(mp.find(prefix[i] - k) != mp.end())
{
ans += mp[prefix[i] - k]; // if yes, then add it our answer
}
mp[prefix[i]]++; // put prefix sum into our map
}
return ans; // and at last, return our answer
}
};
//Input
//nums =
//[1,1,1]
//k = 2
//Output
//2