1279. Parity Zigzag Run
A light panel shows a row of numbers, and the designer wants the longest stretch that looks like a zigzag: in a zigzag, any two neighbouring numbers have different parity, so one is even and the other is odd. Parity of a negative number is the parity of its absolute value, so -3 is odd and -4 is even. Zero is even.
Return the length of the longest contiguous subarray of nums in which every pair of adjacent elements has different parity. A subarray with a single element counts, so the answer is always at least 1. Scan once and keep the length of the current alternating run, restarting it at length 1 whenever two neighbours share a parity. Aim for O(n) time and O(1) extra space.
Example 1
- Input:
- nums = [1,2,3,5,6,7]
- Output:
- 3
- Explanation:
The stretch 1, 2, 3 alternates and so does 5, 6, 7, but 3 and 5 share a parity, so the longest is 3.
Example 2
- Input:
- nums = [2,4,6]
- Output:
- 1
- Explanation:
Every neighbouring pair is even-even, so only single elements qualify and the answer is 1.
Constraints
1 ≤ nums.length ≤ 1000
-109 ≤ nums[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)