Contiguous Array Balance
MediumPrefix Sum · Meta
You are given a binary array nums (every element is 0 or 1). Return the length of the longest contiguous subarray that contains an equal number of 0s and 1s.
If no such subarray exists, return 0.
Example 1
- Input:
- nums = [0,1,1,0,1,1,1,0]
- Output:
- 4
- Explanation
nums[0..3] = [0,1,1,0]has two 0s and two 1s, length 4. Every longer window has more 1s than 0s.
Example 2
- Input:
- nums = [1,1,0,1,0,0,1]
- Output:
- 6
- Explanation
- Both
nums[0..5] = [1,1,0,1,0,0]andnums[1..6] = [1,0,1,0,0,1]hold three 0s and three 1s, so the answer is 6. The whole array has odd length 7, so it cannot balance.
Example 3
- Input:
- nums = [1]
- Output:
- 0
- Explanation
- A single element can never contain the same number of 0s and 1s, so the answer is 0.
Constraints
1 <= nums.length <= 10^5nums[i]is either0or1