Count of subarrays with average K | C ++ implementation of above approach ; Function to count subarray having average exactly equal to K ; To Store the final answer ; Calculate all subarrays ; Calculate required average ; Check if average is equal to k ; Required average found ; Increment res ; Driver code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countKAverageSubarrays ( int arr [ ] , int n , int k ) { int res = 0 ; for ( int L = 0 ; L < n ; L ++ ) { int sum = 0 ; for ( int R = L ; R < n ; R ++ ) { sum += arr [ R ] ; int len = ( R - L + 1 ) ; if ( sum % len == 0 ) { int avg = sum / len ; if ( avg == k ) res ++ ; } } } return res ; } int main ( ) { int K = 6 ; int arr [ ] = { 12 , 5 , 3 , 10 , 4 , 8 , 10 , 12 , -6 , -1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countKAverageSubarrays ( arr , N , K ) ; }