publicclassSolution {
publicintnumberOfSubarrays(int[] nums, int k) {
int n = nums.length;
int[] prefixOddCnt =newint[n + 1];
for (int i = 0; i < n; i++) {
prefixOddCnt[i + 1]+= prefixOddCnt[i]+ (nums[i]& 1);
}
int l = 0, ans = 0;
for (int r = 0; r < n; r++) {
// Ensure the current window [l, r] has at least k odd numberswhile (l <= r && prefixOddCnt[r + 1]- prefixOddCnt[l]> k) {
l++;
}
// If the current window [l, r] has exactly k odd numbersif (prefixOddCnt[r + 1]- prefixOddCnt[l]== k) {
int i = l; // check how much we can slide l// Count nice subarrays ending at rwhile (i <= r && prefixOddCnt[r + 1]- prefixOddCnt[i]== k) {
ans++;
i++;
}
}
}
return ans;
}
}
⏰ Time complexity: O(n) - where n is the number of elements in nums. O(n) for forming prefix count array and O(n) in sliding window, where each number is processed once. So, total time complexity = O(n) + O(n) = O(n)
🧺 Space complexity: O(n), for the prefixOddCnt array.