#C14497. Longest Balanced Subarray

    ID: 44152 Type: Default 1000ms 256MiB

Longest Balanced Subarray

Longest Balanced Subarray

Given an array consisting only of 0s and 1s, the task is to find the length of the longest contiguous subarray that has an equal number of 0's and 1's. If no such subarray exists, output -1. The solution should efficiently handle large arrays and must correctly process edge cases including empty arrays.

The problem can be solved using the prefix sum method: convert each 0 to -1 and then look for subarrays whose cumulative sum is 0, which indicates an equal number of 0s and 1s. All operations must be optimized for fast execution.

inputFormat

The first line of input contains an integer n representing the number of elements in the array. The second line contains n space-separated integers, each being either 0 or 1.

outputFormat

Output a single integer which is the length of the longest contiguous subarray having an equal number of 0's and 1's. If no such subarray exists, output -1.

## sample
4
0 1 0 1
4