Loading problem...
You are given an array of integers nums and a positive integer k. A contiguous subarray is considered qualifying if it contains exactly k odd numbers.
Your task is to determine and return the total count of qualifying subarrays within the given array.
[1, 2, 3], the subarrays are [1], [2], [3], [1,2], [2,3], and [[1,2,3].num % 2 != 0), such as 1, 3, 5, 7, etc.k odd numbers—no more, no less.The challenge lies in efficiently counting all subarrays that satisfy the qualifying condition. A brute-force approach would examine every possible subarray and count odd numbers, but this would be too slow for large inputs. Consider how you might transform the problem or use running counts to achieve a more efficient solution.
nums = [1,1,2,1,1]
k = 32The qualifying subarrays with exactly 3 odd numbers are [1,1,2,1] (positions 0-3) and [1,2,1,1] (positions 1-4). The array contains four odd numbers (1,1,1,1) and one even number (2). Subarrays [1,1,2,1] includes the first three odd numbers, while [1,2,1,1] includes the last three odd numbers. Both contain exactly 3 odd values, making them qualifying subarrays.
nums = [2,4,6]
k = 10The array [2,4,6] contains only even numbers (2, 4, and 6). Since there are no odd numbers in the entire array, it is impossible to form any subarray with exactly 1 odd number. Therefore, the count of qualifying subarrays is 0.
nums = [2,2,2,1,2,2,1,2,2,2]
k = 216The array has exactly 2 odd numbers at positions 3 and 6 (both are 1). Every qualifying subarray must include both of these odd numbers. The number of such subarrays depends on how many even numbers we can include on the left of position 3 (indices 0,1,2,3 → 4 choices including the odd number) and on the right of position 6 (indices 6,7,8,9 → 4 choices including the odd number). The total count is 4 × 4 = 16 qualifying subarrays.
Constraints