1248. Count Number of Nice Subarrays
Problem description:
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:
1 | Input: nums = [1,1,2,1,1], k = 3 |
Example 2:
1 | Input: nums = [2,4,6], k = 1 |
Example 3:
1 | Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2 |
Solution:
Sliding window
- left right boundary to count if
nums[i:j]
havek
odd numbers - start to count the number of subarray and moving left pointer
i
- notice we end the while loop and move
i
to the next number. The count would rollover to next round whenj
increase because ifnums[j]
is even, then it would create more combinations based on previous.
1 | nums: [0,1,0,0,1], k = 1 |
1 | class Solution: |
Replace even elements with 0 and odd elements with 1.
The problem is then reduced to the number of subarrays with sum k
.
1 | class Solution: |
time complexity: $O(n)$
space complexity: $O(1)$
reference:
related problem: