Skip to content

Commit 64a1987

Browse files
i have put count of 0 and 1s till where the count of 0 and 1 are the same in an array
1 parent 763b95b commit 64a1987

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import java.util.HashMap;
2+
3+
public class countof0and1s {
4+
// longest subarray with given equal number of 0's and 1's
5+
public static void main(String[] args) {
6+
HashMap<Integer,Integer> map = new HashMap<>();
7+
int []arr = {0,1,0,1,1,1,0,0,1,0,1,0,0};
8+
int presum = 0;
9+
int res= Integer.MIN_VALUE;
10+
for (int i = 0; i < arr.length ; i++)
11+
if(arr[i]==0)
12+
arr[i]=-1;
13+
for (int right = 0; right < arr.length; right++) {
14+
presum +=arr[right];
15+
if(map.containsKey(presum))
16+
res=Math.max(res,right- map.get(presum));
17+
if(!map.containsKey(presum))
18+
map.put(presum,right);
19+
if (presum==0)
20+
res = right+1;
21+
}
22+
System.out.println(res);
23+
24+
}
25+
}

0 commit comments

Comments
 (0)