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.
Note:
The length of the given binary array will not exceed 50,000.
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
s = ans = 0
mp = {0: -1}
for i, v in enumerate(nums):
s += 1 if v == 1 else -1
if s in mp:
ans = max(ans, i - mp[s])
else:
mp[s] = i
return ans
class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> mp = new HashMap<>();
mp.put(0, -1);
int s = 0, ans = 0;
for (int i = 0; i < nums.length; ++i) {
s += nums[i] == 1 ? 1 : -1;
if (mp.containsKey(s)) {
ans = Math.max(ans, i - mp.get(s));
} else {
mp.put(s, i);
}
}
return ans;
}
}
class Solution {
public:
int findMaxLength(vector<int>& nums) {
unordered_map<int, int> mp;
int s = 0, ans = 0;
mp[0] = -1;
for (int i = 0; i < nums.size(); ++i)
{
s += nums[i] == 1 ? 1 : -1;
if (mp.count(s)) ans = max(ans, i - mp[s]);
else mp[s] = i;
}
return ans;
}
};
func findMaxLength(nums []int) int {
mp := map[int]int{0: -1}
s, ans := 0, 0
for i, v := range nums {
if v == 0 {
v = -1
}
s += v
if j, ok := mp[s]; ok {
ans = max(ans, i-j)
} else {
mp[s] = i
}
}
return ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}