-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
34 lines (29 loc) · 872 Bytes
/
Copy pathsolution.cpp
File metadata and controls
34 lines (29 loc) · 872 Bytes
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
class Solution
{
public:
// Helper function to count subarrays with at most k odd numbers
int atMost(vector<int> &arr, int k)
{
int left = 0, oddCount = 0, result = 0;
for (int right = 0; right < arr.size(); right++)
{
// If current element is odd, increase odd count
if (arr[right] % 2 == 1)
oddCount++;
// Shrink window if odd count exceeds k
while (oddCount > k)
{
if (arr[left] % 2 == 1)
oddCount--;
left++;
}
// Count subarrays ending at right
result += (right - left + 1);
}
return result;
}
int countSubarrays(vector<int> &arr, int k)
{
return atMost(arr, k) - atMost(arr, k - 1);
}
};