1248. Count Number of Nice Subarrays
T: O(n)
S: O(1)```java
/*
[2,2,2,1,2,2,1,2,2,2,1]
c c c
*/
class Solution {
public int numberOfSubarrays(int[] nums, int k) {
int result = 0;
int count = 0;
int right = 0;
int left = 0;
int n = nums.length;
while (right < n) {
int current = nums[right];
right++;
if (current % 2 == 1) {
k--;
count = 0;
}
while (k == 0) {
if (nums[left] % 2 == 1) {
k++;
}
left++;
count++;
}
result += count;
}
return result;
}
}
/*
using sliding win
T: O(n)
S: O(1)
[1,1,2,1,1]
x
x
4 subarray
[2,2,2,1,2,2,1,2,2,2]
r
k++
l then in the later, if it still even, means we have more count*( even number count)
4 4 4 4
satis -> shrink left
so 4 + 4 + 4 + 4 = 16
[2,2,2,1,2,2,1,2,2,2,1]. if in the later, there's odd, re-cal count, so in this range we have new count = 3 => (2 2 1 2 2 2 1) & (2 1 2 2 2 1) & (1 2 2 2 1)
c c c
when odd = k
shrink left
left++
count++
*/
```latest sliding win
Last updated
Was this helpful?