525. Contiguous Array
Contents
Problem
Given a binary array, find the maximum length of a contiguous subarray with 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
- The length of the given binary array will not exceed 50,000.
Solution
- init
sum - walk throw givven array ,and
sum++if current elemen(nums[idx]) equeal1, andsum--if current element equal-1 - if in map exist elemant with key
sum, compareidx-m[sum]+1andmax; ifmaxif less – setmax=idx-m[sum]+1 - Set to map
m[sum] = idx+1
func findMaxLength(nums []int) int {
max := 0
m := make(map[int]int, 0)
s:=0
m[0]=0
for idx:=range nums {
if nums[idx] == 1{
s+=1
} else {
s-=1
}
_, ok := m[s]
if ok {
if idx-m[s]+1>max {
max = idx-m[s]+1
}
} else {
m[s] = idx+1
}
}
return max
}