- Related Questions & Answers
- Adding elements of an array until every element becomes greater than or equal to k in C++.
- Python - Number of values greater than K in list
- Getting equal or greater than number from the list of numbers in JavaScript
- Count sub-arrays which have elements less than or equal to X in C++
- C++ program to Adding elements of an array until every element becomes greater than or equal to k
- Count the number of words having sum of ASCII values less than and greater than k in C++
- Maximum Side Length of a Square with Sum Less than or Equal to Threshold in C++
- Python Indices of numbers greater than K
- Count of alphabets having ASCII value less than and greater than k in C++
- Maximum OR sum of sub-arrays of two different arrays in C++
- Program to find number of K-Length sublists whose average is greater or same as target in python
- Program to split lists into strictly increasing sublists of size greater than k in Python
- How to get the smallest integer greater than or equal to a number in JavaScript?
- Maximize the size of array by deleting exactly k sub-arrays to make array prime in C++
- JavaScript: Finding nearest prime number greater or equal to sum of digits - JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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

#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)); }

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

3

Advertisements