-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargest Array with 0 sum.java
49 lines (44 loc) · 1.34 KB
/
Largest Array 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
//{ Driver Code Starts
import java.io.*;
import java.util.*;
class Geeks {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine()); // Number of test cases
for (int g = 0; g < t; g++) {
// Read input array as a string, split by space, and convert to integers
String[] str = br.readLine().trim().split(" ");
int arr[] = new int[str.length];
for (int i = 0; i < str.length; i++) {
arr[i] = Integer.parseInt(str[i]);
}
// Print the result from maxLen function
System.out.println(new Solution().maxLen(arr));
System.out.println("~");
}
}
}
// } Driver Code Ends
class Solution {
int maxLen(int arr[]) {
// code here
HashMap<Integer,Integer>mp=new HashMap();
int max=0;
int sum=0;
for(int i=0;i<arr.length;i++){
sum+=arr[i];
if(sum==0){
max=i+1;
}
else{
if(mp.containsKey(sum)){
max=Math.max(max,i-mp.get(sum));
}
else{
mp.put(sum,i);
}
}
}
return max;
}
}