Skip to content

Commit f6cb0c9

Browse files
authored
Create largest_subarray_with_zero_sum.cpp
Program to find longest subarray with zero sum in an array of positive and negative integers.
1 parent 9393133 commit f6cb0c9

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Diff for: largest_subarray_with_zero_sum.cpp

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/* Program to find longest subarray with zero sum in an array of positive and negative integers /*
2+
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
int maxLen(int A[], int n);
7+
8+
int main()
9+
{
10+
int T;
11+
cin >> T;
12+
while (T--)
13+
{
14+
int N;
15+
cin >> N;
16+
int A[N];
17+
for (int i = 0; i < N; i++)
18+
cin >> A[i];
19+
cout << maxLen(A, N) << endl;
20+
}
21+
}
22+
23+
24+
25+
int maxLen(int A[], int n)
26+
{ unordered_map<int,int> a;
27+
int s=0,m=0;
28+
a[0]=-1;
29+
for(int i=0;i<n;++i)
30+
{
31+
s+=A[i];
32+
auto y=a.find(s);
33+
if(y==a.end())
34+
a[s]=i;
35+
else
36+
{
37+
if(i-a[s]>m)
38+
m=i-a[s];
39+
40+
}
41+
42+
43+
}
44+
return m;
45+
}

0 commit comments

Comments
 (0)