[LeetCode] Count Number of Nice Subarrays

1248. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int numberOfSubarrays(vector<int>& A, int k) {
int n = A.size(), res = 0;
deque<int> dq{-1};
for(int i = 0; i < n; i++) {
if(A[i] & 1) dq.push_back(i);
if(dq.size() > k + 1) dq.pop_front();
if(dq.size() == k + 1) res += dq[1] - dq[0];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/01/PS/LeetCode/count-number-of-nice-subarrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.