Count Number of Nice Subarrays
Count subarrays containing exactly k odd numbers by computing the difference of two monotonic sliding windows (atMost(k) - atMost(k - 1)).
01The problem
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
| Input | Output | Why |
|---|---|---|
nums = [1, 1, 2, 1, 1], k = 3 | 2 | The two subarrays are [1, 1, 2, 1] and [1, 2, 1, 1] |
nums = [2, 4, 6], k = 1 | 0 | There are no odd numbers in the array |
nums = [2, 2, 2, 1, 2, 2, 1, 2, 2, 2], k = 2 | 16 | 4 starting positions × 4 ending positions |
Constraints: 1 to 50,000 numbers, 1 ≤ nums[i] ≤ 100,000, 1 ≤ k ≤ nums.length.
Loading the rest of the lesson…