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 Code
code: < ? php function findMaxAverage ( $ arr , $ n , $ k ) { if ( $ k > $ n ) return -1 ; $ sum = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ k ; $ i ++ ) $ sum += $ arr [ $ i ] ; $ max_sum = $ sum ; $ max_end = $ k - 1 ; for ( $ i = $ k ; $ i < $ n ; $ i ++ ) { $ sum = $ sum + $ arr [ $ i ] - $ arr [ $ i - $ k ] ; if ( $ sum > $ max_sum ) { $ max_sum = $ sum ; $ max_end = $ i ; } } return $ max_end - $ k + 1 ; } $ arr = array ( 1 , 12 , -5 , -6 , 50 , 3 ) ; $ k = 4 ; $ n = count ( $ arr ) ; echo " The ▁ maximum ▁ average ▁ subarray ▁ of ▁ " , " length ▁ " , $ k , " ▁ begins ▁ at ▁ index ▁ " , findMaxAverage ( $ arr , $ n , $ k ) ; ? >