Find maximum average subarray of k length | Returns beginning index of maximum average subarray of length k ; Check if ' k ' is valid ; Create and fill array to store cumulative sum . csum [ i ] stores sum of arr [ 0 ] to arr [ i ] ; Initialize max_sm as sum of first subarray ; Find sum of other subarrays and update max_sum if required . ; Return starting index ; Driver program
def findMaxAverage ( arr , n , k ) : NEW_LINE INDENT if k > n : NEW_LINE INDENT return - 1 NEW_LINE DEDENT csum = [ 0 ] * n NEW_LINE csum [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT csum [ i ] = csum [ i - 1 ] + arr [ i ] ; NEW_LINE DEDENT max_sum = csum [ k - 1 ] NEW_LINE max_end = k - 1 NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT curr_sum = csum [ i ] - csum [ i - k ] NEW_LINE if curr_sum > max_sum : NEW_LINE INDENT max_sum = curr_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