LeetCode: Contiguous Array

LeetCode: Contiguous Array

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

Example 1:

1
2
3
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.

Example 2:

1
2
3
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.

Note: The length of the given binary array will not exceed 50,000.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public int findMaxLength(int[] nums) {
if (nums == null || nums.length < 2) return 0;

int sum = 0;
int result = 0;
Map<Integer, Integer> dict = new HashMap<>();
dict.put(0, -1);
for (int i = 0; i < nums.length; i++) {
sum += (nums[i] << 1) - 1;
if (dict.containsKey(sum)) {
result = Math.max(result, i - dict.get(sum));
} else {
dict.put(sum, i);
}
}
return result;
}
}