text: 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
code: function findMaxAverage ( arr , n , k ) { if ( k > n ) return - 1 ; let csum = new Array ( n ) ; csum [ 0 ] = arr [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) csum [ i ] = csum [ i - 1 ] + arr [ i ] ; let max_sum = csum [ k - 1 ] , max_end = k - 1 ; for ( let i = k ; i < n ; i ++ ) { let curr_sum = csum [ i ] - csum [ i - k ] ; if ( curr_sum > max_sum ) { max_sum = curr_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 ) ) ;