|
| 1 | +# [1248. Count Number of Nice Subarrays](https://leetcode.com/problems/count-number-of-nice-subarrays) |
| 2 | + |
| 3 | +--- |
| 4 | + |
| 5 | +title: "Counting Subarrays with Exactly K Odd Numbers" |
| 6 | +summary: "A detailed explanation and implementation of counting subarrays with exactly k odd numbers using a sliding window approach." |
| 7 | +date: "2024年06月22日" |
| 8 | +modifiedDate: "2024年06月22日" |
| 9 | +tags: ["algorithm", "sliding window", "javascript"] |
| 10 | +slug: "counting-subarrays-with-exactly-k-odd-numbers" |
| 11 | + |
| 12 | +--- |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +# Intuition |
| 17 | + |
| 18 | +To solve the problem of counting subarrays with exactly k odd numbers, we can leverage the sliding window technique. The idea is to count the subarrays with at most k odd numbers and subtract the count of subarrays with at most (k-1) odd numbers. This way, we get the count of subarrays with exactly k odd numbers. |
| 19 | + |
| 20 | +# Approach |
| 21 | + |
| 22 | +1. Define a helper function `countSubarraysWithAtMostKOddNumbers` which counts subarrays with at most k odd numbers. |
| 23 | +2. Use a sliding window approach within this helper function to expand and contract the window based on the number of odd numbers in the current window. |
| 24 | +3. In the main function `numberOfSubarrays`, compute the difference between the counts of subarrays with at most k and at most (k-1) odd numbers. |
| 25 | + |
| 26 | +# Complexity |
| 27 | + |
| 28 | +- Time complexity: $$O(n)$$ |
| 29 | +- Space complexity: $$O(1)$$ |
| 30 | + |
| 31 | +# Code |
| 32 | + |
| 33 | +```javascript |
| 34 | +/** |
| 35 | + * @param {number[]} nums |
| 36 | + * @param {number} k |
| 37 | + * @return {number} |
| 38 | + */ |
| 39 | +const countSubarraysWithAtMostKOddNumbers = (nums, k) => { |
| 40 | + if (k < 0) return 0; |
| 41 | + |
| 42 | + let [count, left, right, oddCount] = [0, 0, 0, 0]; |
| 43 | + |
| 44 | + while (right < nums.length) { |
| 45 | + // Increment odd count if the current number is odd |
| 46 | + oddCount += nums[right] % 2 !== 0 ? 1 : 0; |
| 47 | + |
| 48 | + // If oddCount exceeds k, adjust the left pointer |
| 49 | + while (oddCount > k) { |
| 50 | + oddCount -= nums[left] % 2 !== 0 ? 1 : 0; |
| 51 | + left++; |
| 52 | + } |
| 53 | + |
| 54 | + // Count the subarrays ending at `right` with at most k odd numbers |
| 55 | + count += right - left + 1; |
| 56 | + right++; |
| 57 | + } |
| 58 | + |
| 59 | + return count; |
| 60 | +}; |
| 61 | + |
| 62 | +function numberOfSubarrays(nums, k) { |
| 63 | + // The number of subarrays with exactly k odd numbers |
| 64 | + return ( |
| 65 | + countSubarraysWithAtMostKOddNumbers(nums, k) - |
| 66 | + countSubarraysWithAtMostKOddNumbers(nums, k - 1) |
| 67 | + ); |
| 68 | +} |
| 69 | +``` |
0 commit comments