Find the subarray with least average | Prints beginning and ending indexes of subarray of size k with minimum average ; k must be smaller than or equal to n ; Initialize beginning index of result ; Compute sum of first subarray of size k ; Initialize minimum sum as current sum ; Traverse from ( k + 1 ) ' th ▁ element ▁ ▁ to ▁ n ' th element ; Add current item and remove first item of previous subarray ; Update result if needed ; Driver code ; Subarray size
function findMinAvgSubarray ( arr , n , k ) { if ( n < k ) return ; let res_index = 0 ; let curr_sum = 0 ; for ( let i = 0 ; i < k ; i ++ ) curr_sum += arr [ i ] ; let min_sum = curr_sum ; for ( let i = k ; i < n ; i ++ ) { curr_sum += arr [ i ] - arr [ i - k ] ; if ( curr_sum < min_sum ) { min_sum = curr_sum ; res_index = ( i - k + 1 ) ; } } document . write ( " " + res_index + " " + ( res_index + k - 1 ) + " " ) ; } let arr = [ 3 , 7 , 90 , 20 , 10 , 50 , 40 ] ; let k = 3 ; let n = arr . length ; findMinAvgSubarray ( arr , n , k ) ;