Balanced Baskets
A new fruit vendor, Rohan, has a unique way of organizing his baskets. He sells only two types of fruits: apples and bananas. Rohan wants to find the longest continuous stretch of baskets that contains an equal number of apples and bananas. Given the sequence of fruits in Rohan's baskets, can you help him find the length of the longest such stretch?
Input
The first line contains an integer N, the number of baskets. The second line contains N space-separated integers, where 1 represents an apple and 0 represents a banana.
Output
Print a single integer: the maximum length of a contiguous subarray with an equal number of 0s and 1s.
Constraints
1 <= N <= 200000. The array contains only 0s and 1s.
Example 1
7 1 1 0 0 1 0 1
6
The subarray from index 2 to 6 (0-indexed) is [0, 0, 1, 0, 1], which has three 0s and two 1s. The subarray [0, 0, 1, 0] (indices 2 to 5) has three 0s and one 1. The subarray [1, 0, 1, 0] (indices 4 to 7) has two 0s and two 1s, length 4. The subarray [1, 1, 0, 0] (indices 0 to 3) has two 1s and two 0
Example 2
5 1 0 1 0 1
4
The longest balanced subarrays are [1, 0] (indices 0-1) and [0, 1] (indices 1-2) and [1, 0] (indices 2-3) and [0, 1] (indices 3-4), all of length 2.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
7 1 1 0 0 1 0 1
5 1 0 1 0 1