Input: arr[] = {3, 1, 2, 1, 1}, k = 3
Output: 2
Explanation:
Subarrays with 3 odd numbers are {3, 1, 2, 1} and {1, 2, 1, 1}.
Input: arr[] = {2, 1, 9, 3, 1}, k = 2
Output: 4
Explanation:
Subarrays with 2 odd numbers are
{1, 9} {9, 3} {3, 1} {2, 1, 9}
Approach 1: Brute Force.
//C++ code to Count Subarrays with K Odd Numbers. //Brute force #include<iostream> #include <vector> using namespace std; //function to return count of subarrays //with k odd numbers int countOddSubarrays(vector<int>& nums, int k) { int n = nums.size(); int count = 0; //traverse for all possible subarrays for (int i = 0; i < n; i++) { int oddCount = 0; for (int j = i; j < n; j++) { if (nums[j] % 2 == 1) { oddCount++; } if (oddCount == k) { count++; } } } return count; } int main(){ vector<int> nums = {1, 2, 1, 1, 4, 1}; int k = 3; cout << countOddSubarrays(nums, k); }
4
Approach 2: Sliding Window Approach.
//C++ code to Count Subarrays with K Odd Numbers. //Sliding window approach #include<iostream> #include <vector> using namespace std; int subArray(vector<int>& nums, int k) { int count = 0, ans = 0, start = 0, end = 0; int n = nums.size(); // Sliding window approach while(end<n){ if(nums[end]%2==1){ count++; } // Shrink the window until the count //becomes less than or equal to K while(count>k){ if(nums[start]%2==1){ count--; } start++; } ans += end-start+1; end++; } return ans; } // Function to count the number of //subarrays with K odd numbers int countOddSubarrays(vector<int>& nums, int k) { /* difference between number of subarrays with at most k-1 odd elements with number of subarrays with at most k odd elements */ return subArray(nums, k) - subArray(nums, k - 1); } int main(){ vector<int> nums = {2, 1, 9, 3, 1}; int k = 2; cout << countOddSubarrays(nums, k); }
4

Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.