Count Number of Nice Subarrays in C++


Suppose we have an array of integers nums and an integer k. A subarray is known as nice subarray if there are k odd numbers on it. We have to find the number of nice sub-arrays. So if the array is [1,1,2,1,1], and k = 3, then the output will be 2, as the subarrays are [1,1,2,1], and [1,2,1,1]

To solve this, we will follow these steps −

  • ans := 0, n := size of nums array
  • left := 0 and right := 0, and count := 0
  • define an array odd, fill this with all odd values present in nums
  • if length of odd array is >= k, then
    • for i is 0 and j in range k – 1 to size of odd – 1, increase i and j by 1
      • left := odd[i] + 1 if i = 0, otherwise odd[i] – odd[i – 1]
      • right := odd[j] if size of odd – 1 = j, otherwise odd[j + 1] – odd[j]
      • ans := ans + left * right
  • return ans

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int numberOfSubarrays(vector<int>& nums, int k) {
      int ans = 0;
      int n = nums.size();
      int left = 0;
      int right = 0;
      int cnt = 0;
      vector <int> odd;
      for(int i = 0; i < n; i++){
         if(nums[i] % 2 == 1)odd.push_back(i);
      }
      if(odd.size()>=k){
         for(int i = 0, j = k-1; j < odd.size(); i++, j++){
            int left = i==0?odd[i]+1: odd[i] - odd[i-1];
            int right = j==odd.size()-1 ?n-odd[j] : odd[j+1] - odd[j];
            ans += left * right;
         }
      }
      return ans;
   }
};
main(){
   vector<int> v = {1,1,2,1,1};
   Solution ob;
   cout <<ob.numberOfSubarrays(v, 3);
}

Input

[1,1,2,1,1]
3

Output

2

Updated on: 30-Apr-2020

730 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements