Minimize the difference between minimum and maximum elements | Function to minimize the difference between minimum and maximum elements ; Find max and min elements of the array ; Check whether the difference between the max and min element is less than or equal to k or not ; Calculate average of max and min ; If the array element is greater than the average then decrease it by k ; If the array element is smaller than the average then increase it by k ; Find max and min of the modified array ; return the new difference ; Driver code
function minimizeDiff ( arr , n , k ) { let max = Math . max ( ... arr ) ; let min = Math . min ( ... arr ) ; if ( ( max - min ) <= k ) { return ( max - min ) ; } let avg = Math . floor ( ( max + min ) / 2 ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > avg ) { arr [ i ] -= k ; } else { arr [ i ] += k ; } } max = Math . max ( ... arr ) ; min = Math . min ( ... arr ) ; return ( max - min ) ; } let arr = [ 3 , 16 , 12 , 9 , 20 ] ; let n = 5 ; let k = 3 ; document . write ( " " + minimizeDiff ( arr , n , k ) ) ;