-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLargest Subarray Of 0s And 1s.java
More file actions
61 lines (41 loc) · 1.42 KB
/
Largest Subarray Of 0s And 1s.java
File metadata and controls
61 lines (41 loc) · 1.42 KB
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
//https://practice.geeksforgeeks.org/problems/largest-subarray-of-0s-and-1s/1
class GfG
{
/*You are required to complete this method*/
int maxLen(int[] arr) {
int N = arr.length;
int[] sub = new int[N];
int sum = 0;
for(int i = 0; i < arr.length; i++){
int num = arr[i];
if(num == 0) num = -1;
sum += num;
sub[i] = sum;
}
int maxSize = -1;
int start = 0, end = 0;
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < N; i++){
if(sub[i] == 0){
if(i+1 > maxSize){
maxSize = i+1;
start = 0;
end = i;
continue;
}
}
if(map.containsKey(sub[i])){
//find difference
int size = i - map.get(sub[i]);
if(size > maxSize){
maxSize = size;
start = map.get(sub[i]);
end = i;
}
} else
map.put(sub[i], i);
}
if(maxSize == -1) return 0;
return maxSize;
}
}