Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold in C++


Suppose we have an array of integers arr and two integers k and threshold. We have to find the number of sub-arrays of size k and average greater than or equal to the threshold. So if the input is like: [2,2,2,2,5,5,5,8] and k = 3 and threshold = 4, then the output will be 3. Because the subarrays [2,5,5], [5,5,5] and [5,5,8] has the averages 4, 5 and 6 respectively.

To solve this, we will follow these steps −

  • sum := 0, div := k and n := number of elements in array

  • set sum := sum of all elements of arr

  • ret := 0

  • for i := 0 and j in range k to n – 1, increase both i and j by 1

    • if sum / div >= threshold, then increase res by 1

    • decrease sum by arr[i]

    • increase sum by arr[j]

  • if sum / div >= threshold, then increase ret by 1

  • return ret.

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 numOfSubarrays(vector<int>& arr, int k, int threshold) {
      double sum = 0;
      double div = k;
      int n = arr.size();
      for(int i = 0; i < k; i++){
         sum += arr[i];
      }
      int ret = 0;
      for(int i = 0, j = k; j < n; i ++, j++){
         if(sum / div >= threshold ){
            ret++;
         }
         sum -= arr[i];
         sum += arr[j];
      }
      if(sum / div >= threshold ){
         ret++;
      }
      return ret;
   }
};
main(){
   vector<int> v = {2,2,2,2,5,5,5,8};
   Solution ob;
   cout << (ob.numOfSubarrays(v, 3, 4));
}

Input

[2,2,2,2,5,5,5,8]
3
4

Output

3

Updated on: 29-Apr-2020

614 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements