#C13226. Longest Contiguous Subarray with Equal Number of 0s and 1s
Longest Contiguous Subarray with Equal Number of 0s and 1s
Longest Contiguous Subarray with Equal Number of 0s and 1s
Given a binary array nums
consisting only of 0s and 1s, your task is to determine the length of the longest contiguous subarray that contains an equal number of 0s and 1s. This problem requires you to efficiently find a subarray where the number of 0s equals the number of 1s by employing a cumulative sum approach combined with a hash map.
For example, in the array [1, 0, 1, 1, 0, 1, 0, 0]
, the entire array is such a subarray, so the expected output is 8
. If no such subarray exists, output 0
.
Use optimal techniques to ensure your solution can handle large inputs.
inputFormat
The input is given via standard input (stdin). The first line contains an integer n denoting the number of elements in the array. The second line contains n space-separated integers (each either 0 or 1) representing the array.
outputFormat
Output a single integer on stdout representing the length of the longest contiguous subarray with an equal number of 0s and 1s.
## sample8
1 0 1 1 0 1 0 0
8