Minimize difference between maximum and minimum of Array by at most K replacements | Function to find minimum difference between the maximum and the minimum elements arr [ ] by at most K replacements ; Check if turns are more than or equal to n - 1 then simply return zero ; Sort the array ; Set difference as the maximum possible difference ; Iterate over the array to track the minimum difference in k turns ; Return the answer ; Given array arr [ ] ; Given K replacements ; Function Call
function maxMinDifference ( arr , n , k ) { if ( k >= n - 1 ) return 0 ; arr . sort ( ( a , b ) => a - b ) ; let ans = arr [ n - 1 ] - arr [ 0 ] ; for ( let i = k , j = n - 1 ; i >= 0 ; -- i , -- j ) { ans = Math . min ( arr [ j ] - arr [ i ] , ans ) ; } return ans ; } let arr = [ 1 , 4 , 6 , 11 , 15 ] ; let N = arr . length ; let K = 3 ; document . write ( maxMinDifference ( arr , N , K ) ) ;