-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaxLenSubArray0s1s[Array].java
66 lines (58 loc) · 1.63 KB
/
MaxLenSubArray0s1s[Array].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
57
58
59
60
61
62
63
64
65
66
// { Driver Code Starts
import java.util.Scanner;
import java.util.*;
import java.lang.*;
import java.util.HashMap;
class Largest_Subarray {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T > 0) {
int N = sc.nextInt();
int a[] = new int[N];
for (int i = 0; i < N; i++) {
a[i] = sc.nextInt();
}
GfG g = new GfG();
int n = g.maxLen(a, a.length);
System.out.println(n);
T--;
}
}
}
// } Driver Code Ends
class GfG {
// arr[] : the input array containing 0s and 1s
// N : size of the input array
// return the maximum length of the subarray
// with equal 0s and 1s
int maxLen(int[] arr, int n) {
int sum =0;
int end_pos = -1;
int len=0;
if(n==1){
return 0;//array size is 0 means no sub array
}
Map<Integer,Integer> hmp = new HashMap<Integer,Integer>();
hmp.put(0,-1);
for(int i=0;i<n;i++){
sum+=(arr[i]==0?-1:1);
//sum was already identified and finding again means
//we founds the subarray of size 0
if(hmp.containsKey(sum)){
if(len < i-hmp.get(sum)){
len = i-hmp.get(sum);
end_pos = i;
}
} else {
//sum found first time
hmp.put(sum,i);
}
}//end of for loop
if(end_pos==-1){
return 0;
} else {
return len;
}
}
}