Code Logo

Longest Alternating Parity Subarray

Published atDate not available
Medium 0 views
Like0

This problem asks for the length of the longest continuous part of the list where the numbers keep switching between odd and even. If one number is odd, the next should be even. If one number is even, the next should be odd.

You are looking for a subarray, so the numbers must stay next to each other in the original list. You are not allowed to skip values. The answer is only the length of the best stretch, not the stretch itself.

For example, in [1,1,2,3], the best alternating subarray is [1,2,3], so the answer is 3. In [3,2,5,8,7,6], the whole list alternates odd, even, odd, even, odd, even, so the answer is 6. If a list has no alternation at all, like [4,4,4,4], the best answer is just 1 because any single number works by itself.

The important part is to notice where the alternating pattern breaks and where a new stretch should begin.

Example Input & Output

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

The longest alternating subarray is [1,2,3], with length 3.

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

The entire array alternates odd-even-odd-even-odd-even.

Example 3
Input
nums = [4,4,4,4]
Output
1
Explanation

No alternation occurs, so the maximum length is 1.

Algorithm Flow

Recommendation Algorithm Flow for Longest Alternating Parity Subarray
Recommendation Algorithm Flow for Longest Alternating Parity Subarray

Best Answers

java
class Solution {
    public int longest_alternating_subarray(int[] nums) {
        if (nums.length == 0) return 0;
        int maxLen = 1, current = 1;
        for (int i = 1; i < nums.length; i++) {
            if (Math.abs(nums[i] % 2) != Math.abs(nums[i-1] % 2)) current++;
            else current = 1;
            maxLen = Math.max(maxLen, current);
        }
        return maxLen;
    }
}