Code Logo

Longest Balanced Subarray

Published atDate not available
Easy 0 views
Like0

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

Example 1
Input
nums = [2,5,6,3,4,7]
Output
6
Explanation

The entire array has three evens and three odds, forming the longest balanced subarray.

Example 2
Input
nums = [1,3,5,7]
Output
0
Explanation

There is no subarray where even and odd counts match.

Example 3
Input
nums = [2,4,1,3,6,8,5,7]
Output
8
Explanation

The full array balances four even numbers with four odd numbers.

Algorithm Flow

Recommendation Algorithm Flow for Longest Balanced Subarray
Recommendation Algorithm Flow for Longest Balanced Subarray

Best Answers

java
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;
    }
}