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
< ? php function minimizeDiff ( & $ arr , $ n , $ k ) { $ max = max ( $ arr ) ; $ min = min ( $ arr ) ; if ( ( $ max - $ min ) <= $ k ) { return ( $ max - $ min ) ; } $ avg = ( $ max + $ min ) / 2 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] > $ avg ) $ arr [ $ i ] -= $ k ; else $ arr [ $ i ] += $ k ; } $ max = max ( $ arr ) ; $ min = min ( $ arr ) ; return ( $ max - $ min ) ; } $ arr = array ( 3 , 16 , 12 , 9 , 20 ) ; $ n = 5 ; $ k = 3 ; echo " Max ▁ height ▁ difference ▁ = ▁ " . minimizeDiff ( $ arr , $ n , $ k ) . " STRNEWLINE " ; ? >