Minimize difference between maximum and minimum array elements by removing a K | Function to minimize difference between maximum and minimum array elements by removing a K - length subarray ; Size of array ; Stores the maximum and minimum in the suffix subarray [ i . . N - 1 ] ; Traverse the array ; Stores the maximum and minimum in the prefix subarray [ 0 . . i - 1 ] ; Store the minimum difference ; Traverse the array ; If the suffix doesn 't exceed  the end of the array ; Store the maximum element in array after removing subarray of size K ; Stores the maximum element in array after removing subarray of size K ; Update minimum difference ; Updating the maxPrefix and minPrefix with current element ; Print the minimum difference ; Driver Code
function minimiseDifference ( arr , K ) { var N = arr . length ; var maxSuffix = new Array ( N + 1 ) ; var minSuffix = new Array ( N + 1 ) ; maxSuffix [ N ] = - 1e9 ; minSuffix [ N ] = 1e9 ; maxSuffix [ N - 1 ] = arr [ N - 1 ] ; minSuffix [ N - 1 ] = arr [ N - 1 ] ; for ( var i = N - 2 ; i >= 0 ; -- i ) { maxSuffix [ i ] = Math . max ( maxSuffix [ i + 1 ] , arr [ i ] ) ; minSuffix [ i ] = Math . min ( minSuffix [ i + 1 ] , arr [ i ] ) ; } var maxPrefix = arr [ 0 ] ; var minPrefix = arr [ 0 ] ; var minDiff = maxSuffix [ K ] - minSuffix [ K ] ; for ( var i = 1 ; i < N ; ++ i ) { if ( i + K <= N ) { var maximum = Math . max ( maxSuffix [ i + K ] , maxPrefix ) ; var minimum = Math . min ( minSuffix [ i + K ] , minPrefix ) ; minDiff = Math . min ( minDiff , maximum - minimum ) ; } maxPrefix = Math . max ( maxPrefix , arr [ i ] ) ; minPrefix = Math . min ( minPrefix , arr [ i ] ) ; } document . write ( minDiff + " " ) ; } var arr = [ 4 , 5 , 8 , 9 , 1 , 2 ] ; var K = 2 ; minimiseDifference ( arr , K ) ;