#K10036. Longest Subarray with Equal Number of Even and Odd Numbers
Longest Subarray with Equal Number of Even and Odd Numbers
Longest Subarray with Equal Number of Even and Odd Numbers
You are given an array of N integers. Your task is to find the length of the longest contiguous subarray that contains an equal number of even and odd numbers.
How to Solve: Convert each number into a value: assign +1
for odd numbers and -1
for even numbers. Then, the problem reduces to finding the longest subarray with a sum of 0 using prefix sum techniques.
Note: Use efficient algorithms to achieve an optimal solution as this problem might be tested with large input sizes.
inputFormat
The first line contains a single integer N — the size of the array.
The second line contains N space-separated integers — the elements of the array.
outputFormat
Output a single integer — the length of the longest subarray that has an equal number of even and odd numbers. If no such subarray exists, output 0
.
5
1 2 3 4 5
4