Minimize difference between maximum and minimum array elements by exactly K removals | Function to minimize the difference of the maximum and minimum array elements by removing K elements ; Base Condition ; Sort the array ; Initialize left and right pointers ; Iterate for K times ; Removing right element to reduce the difference ; Removing the left element to reduce the difference ; Print the minimum difference ; Driver Code ; Function Call
function minimumRange ( arr , N , K ) { if ( K >= N ) { document . write ( 0 ) ; return ; } arr . sort ( ( a , b ) => a - b ) ; var left = 0 , right = N - 1 , i ; for ( i = 0 ; i < K ; i ++ ) { if ( arr [ right - 1 ] - arr [ left ] < arr [ right ] - arr [ left + 1 ] ) right -- ; else left ++ ; } document . write ( arr [ right ] - arr [ left ] ) ; } var arr = [ 5 , 10 , 12 , 14 , 21 , 54 , 61 ] ; var N = arr . length ; var K = 4 ; minimumRange ( arr , N , K ) ;