Longest Balanced Subarray
This problem asks for the length of the longest continuous part of the list where the number of even values and odd values is equal. That balanced stretch can begin anywhere and end anywhere, as long as the numbers stay together in one unbroken subarray.
The answer is just a number showing how long the best balanced subarray is. If the whole list has the same number of evens and odds, then the answer is the full length of the list. If there is no balanced subarray at all, the answer should be 0.
For example, [2,5,6,3,4,7] has three evens and three odds, so the whole list is balanced and the answer is 6. But [1,3,5,7] has only odd numbers, so there is no balanced subarray and the answer is 0.
The important part is that you are counting evens and odds inside continuous stretches, not inside random picks from the list. You are searching for the longest valid range, not just any valid range.
Example Input & Output
The entire array has three evens and three odds, forming the longest balanced subarray.
There is no subarray where even and odd counts match.
The full array balances four even numbers with four odd numbers.
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public int find_longest_balanced_segment(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int maxLen = 0, current = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) current++;
else if (nums[i] < 0) current--;
else continue;
if (map.containsKey(current)) maxLen = Math.max(maxLen, i - map.get(current));
else map.put(current, i);
}
return maxLen;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
