15. Count Number of Nice Subarrays

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.

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: (Sliding Window)

Approach: We find the position of odd number We then calculate the maximum expansion possible on both sides Number of subarrays = number of element on left * number of element on right

class Solution
{
public:
    int numberOfSubarrays(vector<int> &nums, int k)
    {

        int n = nums.size();
        vector<int> oddArr;
        oddArr.push_back(-1);

        for (int i = 0; i < nums.size(); i++)
        {
            if (nums[i] % 2 != 0)
            {
                oddArr.push_back(i);
            }
        }

        if (oddArr.size() < k + 1)
        {
            return 0;
        }
        oddArr.push_back(n);

        int res = 0;

        for (int i = 1; i < oddArr.size() - 1; i++)
        {

            int j = i + k - 1;
            if (j < oddArr.size() - 1)
            {

                int leftLimit = oddArr[i] - oddArr[i - 1];
                int rightLimit = oddArr[j + 1] - oddArr[j];

                res += leftLimit * rightLimit;
            }
        }

        return res;
    }
};

Time Complexity: O(n) Space Complexity: O(n)

Last updated