525 Contiguous Array

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

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= nums.length <= 105
  • nums[i] is either 0 or 1.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def findMaxLength(self, nums: List[int]) -> int:
        max_len = 0
        h = {}
        count = 0
        for i, n in enumerate(nums):
            count += 1 if n == 1 else -1
            
            if count == 0:
                max_len = i + 1
            if count in h:
                max_len = max(max_len, i - h[count])
            else:
                h[count] = i
        return max_len
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
func findMaxLength(nums []int) int {
	m := make(map[int]int)
	m[0] = -1
	max := 0
	current := 0
	for i, v := range nums {
		if v == 0 {
			current--
		} else {
			current++
		}
		if j, ok := m[current]; ok {
			if i-j > max {
				max = i - j
			}
		} else {
			m[current] = i
		}
	}
	return max
}