Minimize count of array elements to be removed to maximize difference between any pair up to K | Function to count the number of elements to be removed from the array based on the given condition ; Sort the array ; / Initialize the variable ; Iterate for all possible pairs ; Check the difference between the numbers ; Update the minimum removals ; Return the answer ; Driver Code
function min_remove ( arr , n , k ) { arr . sort ( ) ; let ans = Number . MAX_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = i ; j < n ; j ++ ) { if ( arr [ j ] - arr [ i ] <= k ) { ans = Math . min ( ans , n - j + i - 1 ) ; } } } return ans ; } let k = 3 ; let arr = [ 1 , 2 , 3 , 4 , 5 ] ; let n = arr . length ; document . write ( min_remove ( arr , n , k ) ) ;