-
Notifications
You must be signed in to change notification settings - Fork 0
/
Largest subarray with 0 sum.cpp
53 lines (44 loc) · 1.1 KB
/
Largest subarray with 0 sum.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
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
/*You are required to complete this function*/
class Solution {
public:
// Function to find the length of the longest subarray with sum 0.
int maxLen(vector<int>& A, int n) {
unordered_map<int, int> sumIndex;
int maxLength = 0;
int currentSum = 0;
for (int i = 0; i < n; i++) {
currentSum += A[i];
if (currentSum == 0) {
maxLength = max(maxLength, i + 1);
} else {
if (sumIndex.find(currentSum) != sumIndex.end()) {
maxLength = max(maxLength, i - sumIndex[currentSum]);
} else {
sumIndex[currentSum] = i;
}
}
}
return maxLength;
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int m;
cin>>m;
vector<int> array1(m);
for (int i = 0; i < m; ++i){
cin>>array1[i];
}
Solution ob;
cout<<ob.maxLen(array1,m)<<endl;
}
return 0;
}