website/content.en/ChapterFour/0500~0599/0525.Contiguous-Array.md
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.
Constraints:
1 <= nums.length <= 105nums[i] is either 0 or 1.Given a binary array nums, find the longest contiguous subarray containing the same number of 0s and 1s, and return the length of that subarray.
package leetcode
func findMaxLength(nums []int) int {
dict := map[int]int{}
dict[0] = -1
count, res := 0, 0
for i := 0; i < len(nums); i++ {
if nums[i] == 0 {
count--
} else {
count++
}
if idx, ok := dict[count]; ok {
res = max(res, i-idx)
} else {
dict[count] = i
}
}
return res
}
func max(a, b int) int {
if a > b {
return a
}
return b
}