Count of subarrays of size K with average at least M | C ++ program for the above approach ; Function to count the subarrays of size K having average at least M ; Stores the resultant count of subarray ; Stores the sum of subarrays of size K ; Add the values of first K elements to the sum ; Increment the count if the current subarray is valid ; Traverse the given array ; Find the updated sum ; Check if current subarray is valid or not ; Return the count of subarrays ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int countSubArrays ( int arr [ ] , int N , int K , int M ) { int count = 0 ; int sum = 0 ; for ( int i = 0 ; i < K ; i ++ ) { sum += arr [ i ] ; } if ( sum >= K * M ) count ++ ; for ( int i = K ; i < N ; i ++ ) { sum += ( arr [ i ] - arr [ i - K ] ) ; if ( sum >= K * M ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 3 , 6 , 3 , 2 , 1 , 3 , 9 } ; int K = 2 , M = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSubArrays ( arr , N , K , M ) ; return 0 ; }