leetcode 1248 - Count Number of Nice Subarrays

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

Constraints:

1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
int size = nums.size();
unordered_map<int, int> count;
int total = 0;
int odd = 0;

count[0] = 1;

for (int i = 0; i < size; i++) {
odd += nums[i] % 2;

total += count[odd - k];
count[odd]++;

for (int i = 0; i < odd - k; i++) {
if (count.count(i) == 0)
break;
count.erase(i);
}
}

return total;
}
};

//Space O(1)
class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
return atMostK(nums, k) - atMostK(nums, k-1);
}

int atMostK(vector<int>& nums, int k) {
int size = nums.size();
int odd = 0;
int total = 0;

int i = 0;
for (int j = 0; j < size; j++) {
odd += nums[j] % 2;

while (odd > k) {
odd -= nums[i++] % 2;
}

total += j - i + 1;
}

return total;
}
};