text: Find maximum average subarray of k length | Returns beginning index of maximum average subarray of length k ; Check if ' k ' is valid ; Compute sum of first ' k ' elements ; Compute sum of remaining subarrays ; Return starting index ; Driver program
code: def findMaxAverage ( arr , n , k ) : NEW_LINE INDENT if ( k > n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT sum = arr [ 0 ] NEW_LINE for i in range ( 1 , k ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT max_sum = sum NEW_LINE max_end = k - 1 NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT sum = sum + arr [ i ] - arr [ i - k ] NEW_LINE if ( sum > max_sum ) : NEW_LINE INDENT max_sum = sum NEW_LINE max_end = i NEW_LINE DEDENT DEDENT return max_end - k + 1 NEW_LINE DEDENT arr = [ 1 , 12 , - 5 , - 6 , 50 , 3 ] NEW_LINE k = 4 NEW_LINE n = len ( arr ) NEW_LINE print ( " The ▁ maximum ▁ average ▁ subarray ▁ of ▁ length " , k , " begins ▁ at ▁ index " , findMaxAverage ( arr , n , k ) ) NEW_LINE