Minimize difference between the largest and smallest array elements by K replacements | Function to find minimum difference between largest and smallest element after K replacements ; Sort array in ascending order ; Length of array ; Minimum difference ; Check for all K + 1 possibilities ; Return answer ; Given array ; Prints the minimum possible difference
function minDiff ( A , K ) { A . sort ( function ( a , b ) { return a - b } ) ; let n = A . length ; if ( n <= K ) return 0 ; let mindiff = A [ n - 1 ] - A [ 0 ] ; if ( K == 0 ) return mindiff ; for ( let i = 0 , j = n - 1 - K ; j < n ; ) { mindiff = Math . min ( mindiff , A [ j ] - A [ i ] ) ; i ++ ; j ++ ; } return mindiff ; } let A = [ - 1 , 3 , - 1 , 8 , 5 , 4 ] ; let K = 3 ; document . write ( minDiff ( A , K ) ) ;