Count Subarrays with Equal Even and Odd Counts
Problem statement
You are given an integer array nums. A subarray is balanced when it contains as many even values as odd values.
Return the number of balanced subarrays. A subarray is a contiguous, non-empty part of the array. Subarrays that start or end at different indices are counted separately, even when they hold the same values.
Function
countBalancedSubarrays(nums: int[]) → longExamples
Example 1
nums = [3,8,5,6]return = 4The numbers alternate between odd and even. The balanced subarrays are [3, 8], [8, 5], [5, 6] and the whole array [3, 8, 5, 6], which has two even and two odd numbers. A subarray of odd length can never be balanced, and these four are all the subarrays of even length, so the answer is 4.
Example 2
nums = [4,10,2]return = 0All three numbers are even, so every subarray has more even numbers than odd numbers. No subarray is balanced.
Example 3
nums = [7,0,2,9,9]return = 40 is even. The balanced subarrays are [7, 0], [2, 9], [0, 2, 9, 9] and [7, 0, 2, 9]. For example, [0, 2, 9, 9] has the even numbers 0 and 2 and the odd numbers 9 and 9.
Constraints
1 <= nums.length <= 10^50 <= nums[i] <= 10^9