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
function findMaxAverage ( arr , n , k ) { if ( k > n ) return - 1 ; let sum = arr [ 0 ] ; for ( let i = 1 ; i < k ; i ++ ) sum += arr [ i ] ; let max_sum = sum ; let max_end = k - 1 ; for ( let 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 ; } let arr = [ 1 , 12 , - 5 , - 6 , 50 , 3 ] ; let k = 4 ; let n = arr . length ; document . write ( " " + " " + k + " " + findMaxAverage ( arr , n , k ) ) ;