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 Code
< ? php function findMaxAverage ( $ arr , $ n , $ k ) { if ( $ k > $ n ) return -1 ; $ csum = array ( ) ; $ csum [ 0 ] = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) $ csum [ $ i ] = $ csum [ $ i - 1 ] + $ arr [ $ i ] ; $ max_sum = $ csum [ $ k - 1 ] ; $ max_end = $ k - 1 ; for ( $ i = $ k ; $ i < $ n ; $ i ++ ) { $ curr_sum = $ csum [ $ i ] - $ csum [ $ i - $ k ] ; if ( $ curr_sum > $ max_sum ) { $ max_sum = $ curr_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 ) ; ? >