# 1248. Count Number of Nice Subarrays

Given an array of integers nums and an integer k. A subarray is called nice if there are k odd numbers on it.

Return the number of nice sub-arrays.

Example 1:

Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].

Example 2:

Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There is no odd numbers in the array.

Example 3:

Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16

# Solution

Approach 1: sliding window. Pick out all indices of odd numbers, then calculate the boundaries for each window.

# Code (Python)

Approach 1:

class Solution:
    def numberOfSubarrays(self, nums: List[int], k: int) -> int:
        # idea: sliding window. Pick out all indices of odd numbers, then calculate the boundaries for each window.
        odd_indices = [i for i in range(len(nums)) if nums[i] % 2 == 1]
        if k > len(odd_indices):
            return 0
        count = 0
        for end_index in range(k-1, len(odd_indices)):
            start_index = end_index - k + 1
            left = odd_indices[start_index] - odd_indices[start_index-1] if start_index-1 >= 0 else odd_indices[start_index] + 1
            right = odd_indices[end_index+1] - odd_indices[end_index] if end_index + 1 < len(odd_indices) else len(nums) - odd_indices[end_index]
            count += left * right
        return count

# Code (C++)

Approach 1:

Approach 2: