1248. Count Number of Nice Subarrays

https://leetcode.com/contest/weekly-contest-161/problems/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

Constraints:

  • 1 <= nums.length <= 50000

  • 1 <= nums[i] <= 10^5

  • 1 <= k <= nums.length

问刚好有K个奇数的子数组个数。问题围绕子数组和K,动态窗口或DP。用c记录下窗口内奇数的个数,当窗口内奇数个数等于K时前移l直到c再次小于K。前移时[l, r - 1]就是符合条件的一个子数组,增加res,但只增加1的话,对于22212122这样的数组后面两个2和前面的2221能各组成四个新子数组就丢失了。因此再额外用t记录下对于当前l窗口移动了几个格,之后的r扩展时只要不是奇数(会触发l新前移),res就增加t。

class Solution {
public:
    int numberOfSubarrays(vector<int>& nums, int k) {
        const int N = nums.size();
        int l = 0, r = 0, c = 0, res = 0, t = 0;
        while (r < N) {
            if (nums[r] & 1 == 1) {
                ++c;
                t = 0;
            }
            while (c == k) {
                if (nums[l++] & 1 == 1) --c;
                ++t;
            }
            res += t;
            ++r;
        } 

        return res;
    }
};

Last updated