Problem 505
Count Subarrays with K Odd Numbers
Medium · 20 pts · Array, Prefix Sum, Sliding Window
Problem
Count the non-empty blocks of consecutive elements that contain exactly K odd numbers. Blocks at different positions count separately. Replace every number by 1 if it is odd and 0 if it is even; the task becomes counting blocks with sum exactly K, which a running prefix count solves in one pass. Remember that negative numbers can be odd too.
Input
The first line contains N and K. The second line contains N integers.
Output
Print the number of subarrays with exactly K odd numbers.
Constraints
1 <= N <= 50000; -100000 <= A[i] <= 100000; 1 <= K <= N
Example input
5 3 1 1 2 1 1
Example output
2
Explanation
In 1 1 2 1 1 with K = 3, the blocks with exactly three odd numbers are 1 1 2 1 (the first four elements) and 1 2 1 1 (the last four). So the answer is 2.