-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlong_subarray_with_k.cpp
More file actions
46 lines (41 loc) · 1.16 KB
/
Copy pathlong_subarray_with_k.cpp
File metadata and controls
46 lines (41 loc) · 1.16 KB
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
#include <bits/stdc++.h>
using namespace std;
// compute length of the longest subarray with sum 0
int solve(vector<int>& a) {
// store best length found so far
int maxLen = 0;
// map prefix sum -> first index seen
unordered_map<int, int> sumIndexMap;
// running prefix sum
int sum = 0;
// iterate through the array
for (int i = 0; i < (int)a.size(); i++) {
// update running sum
sum += a[i];
// if sum is zero, subarray [0..i] has zero sum
if (sum == 0) {
// update best length
maxLen = i + 1;
}
// if this sum seen before, subarray (prevIndex..i] has zero sum
else if (sumIndexMap.find(sum) != sumIndexMap.end()) {
// maximize length using previous index
maxLen = max(maxLen, i - sumIndexMap[sum]);
}
// first time seeing this sum, store its index
else {
sumIndexMap[sum] = i;
}
}
// return best length
return maxLen;
}
// program entry
int main() {
// sample input
vector<int> a = {9, -3, 3, -1, 6, -5};
// print result
cout << solve(a) << endl;
// exit
return 0;
}