Count of subarrays with average K | 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
def countKAverageSubarrays ( arr , n , k ) : NEW_LINE INDENT res = 0 NEW_LINE for L in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for R in range ( L , n , 1 ) : NEW_LINE INDENT sum += arr [ R ] NEW_LINE len1 = ( R - L + 1 ) NEW_LINE if ( sum % len1 == 0 ) : NEW_LINE INDENT avg = sum // len1 NEW_LINE if ( avg == k ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 6 NEW_LINE arr = [ 12 , 5 , 3 , 10 , 4 , 8 , 10 , 12 , - 6 , - 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countKAverageSubarrays ( arr , N , K ) ) NEW_LINE DEDENT