-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargest subarray with 0 sum.java
57 lines (48 loc) · 1.09 KB
/
Largest subarray with 0 sum.java
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
// code start
// { Driver Code Starts
import java.util.*;
class MaxLenZeroSumSub
{
// Returns length of the maximum length subarray with 0 sum
// Drive method
public static void main(String arg[])
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T > 0)
{
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
GfG g = new GfG();
System.out.println(g.maxLen(arr, n));
T--;
}
}
}// } Driver Code Ends
class GfG
{
int maxLen(int arr[], int n)
{
// Your code here
HashMap<Integer,Integer> hm = new HashMap<>();
int res=0,sum=0;
hm.put(0,-1);
for(int i=0;i<n;i++)
{
sum+=arr[i];
if(!hm.containsKey(sum))
{
hm.put(sum,i);
}
else
{
int idx=hm.get(sum);
res=Math.max(res,i-idx);
}
}
return res;
}
}
// code end