leetcode/0525.Contiguous-Array/README.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.给定一个二进制数组 nums , 找到含有相同数量的 0 和 1 的最长连续子数组,并返回该子数组的长度。
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
}