Count Alternating-Parity Subarrays
Problem statement
You are given an integer array nums.
A contiguous subarray is alternating when every pair of adjacent elements has different parity: one is even and the other is odd. Every one-element subarray is alternating.
Return the total number of alternating contiguous subarrays.
Function
countAlternatingParitySubarrays(nums: int[]) → longExamples
Example 1
nums = [1,3,5,7,9]return = 5Every adjacent pair has odd-odd parity, so only the five one-element subarrays qualify.
Example 2
nums = [1,2,1,2,1]return = 15The entire array alternates. All 5 * 6 / 2 = 15 contiguous subarrays therefore qualify.
Example 3
nums = [1,2,3,7,6,5]return = 12The equal-parity pair 3, 7 splits the array into two alternating runs of length 3. Each contributes 3 * 4 / 2 = 6 subarrays.
Constraints
1 <= nums.length <= 105-109 <= nums[i] <= 109- The answer fits in a signed 64-bit integer.