-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContiguous_Array.java
More file actions
55 lines (44 loc) · 1.27 KB
/
Copy pathContiguous_Array.java
File metadata and controls
55 lines (44 loc) · 1.27 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
/*
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
Example 1:
Input: nums = [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
Example 2:
Input: nums = [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Example 3:
Input: nums = [0,1,1,1,1,1,0,0,0]
Output: 6
Explanation: [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1.
Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1.
*/
import java.util.*;
class Contiguous_Array {
public int findMaxLength(int[] nums) {
int zero = 0;
int one = 0;
int result = 0 ;
HashMap <Integer , Integer> map = new HashMap <>();
map.put(0,-1);
for(int i = 0; i<nums.length ; i++){
if(nums[i]==0){
zero += 1;
}
else{
one += 1;
}
int diff = one - zero ;
if(!map.containsKey (diff)){
map.put(diff , i);
}
if(map.containsKey(diff)){
result = Math.max(result , (i-map.get(diff)));
}
}
return result;
}
}