Leetcode 525. Contiguous Array
1 min readFeb 4, 2022
[medium]
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 <= 105
nums[i]
is either0
or1
.
[Think]
- I was think using sliding window in this question, and hashmap would be good to notice current total sum.
- if we found another number with the same sum, which mean they have the same 0 and 1 between them. calculate the different between these two number
3. map.put(0, -1) -> current sum equal 0, add the first one if total array equal to 0.
[Java]