Sliding Window Counting windows
183. Count Number of Nice Subarrays
You are given an array of integers nums and an integer k. A subarray is nice when exactly k of its
elements are odd numbers. Return the number of nice subarrays.
A subarray is a contiguous sequence of elements from nums, with at least one element. Two subarrays are
different if they start or end at different positions.
Example 1
Input: nums = [4, 7, 2, 9, 6, 5], k = 2
6Explanation: Six subarrays hold exactly two odd numbers. Four hold 7 and 9: [4,7,2,9], [7,2,9], [4,7,2,9,6] and
[7,2,9,6]. Two hold 9 and 5: [2,9,6,5] and [9,6,5].
Example 2
Input: nums = [-3, 0, 8, -5], k = 1
6Explanation: -3 and -5 are odd, and 0 and 8 are even. Three subarrays hold -3 without -5, and three hold
-5 without -3.
Example 3
Input: nums = [10, 4, 1, 8], k = 0
4Explanation: With k = 0, a nice subarray holds no odd number. The four are [10], [4], [10,4] and [8].
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 1090 ≤ k ≤ nums.length
Clarifying questions
What you would ask an interviewer before writing any code.