Longest Alternating Parity Subarray
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
The longest alternating subarray is [1,2,3], with length 3.
The entire array alternates odd-even-odd-even-odd-even.
No alternation occurs, so the maximum length is 1.
Algorithm Flow

Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
