Difference between maximum and minimum average of all K | Function to find the difference between the maximum and minimum subarrays of length K ; Stores the sum of subarray over the range [ 0 , K ] ; Iterate over the range [ 0 , K ] ; Store min and max sum ; Iterate over the range [ K , N - K ] ; Increment sum by arr [ i ] - arr [ i - K ] ; Update max and min moving sum ; Return difference between max and min average ; Given Input ; Function Call
function Avgdifference ( arr , N , K ) { let sum = 0 ; for ( let i = 0 ; i < K ; i ++ ) sum += arr [ i ] ; let min = sum ; let max = sum ; for ( let i = K ; i <= N - K + 1 ; i ++ ) { sum += arr [ i ] - arr [ i - K ] ; if ( min > sum ) min = sum ; if ( max < sum ) max = sum ; } return ( max - min ) / K ; } let arr = [ 3 , 8 , 9 , 15 ] ; let N = arr . length ; let K = 2 ; document . write ( Avgdifference ( arr , N , K ) ) ;