Minimize the difference between minimum and maximum elements | Java program to 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
import java . util . * ; class GFG { static int minimizeDiff ( int [ ] arr , int n , int k ) { int max = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; int min = Arrays . stream ( arr ) . min ( ) . getAsInt ( ) ; if ( ( max - min ) <= k ) { return ( max - min ) ; } int avg = ( max + min ) / 2 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > avg ) { arr [ i ] -= k ; } else { arr [ i ] += k ; } } max = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; min = Arrays . stream ( arr ) . min ( ) . getAsInt ( ) ; return ( max - min ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 16 , 12 , 9 , 20 } ; int n = 5 ; int k = 3 ; System . out . println ( " Max ▁ height ▁ difference ▁ = ▁ " + minimizeDiff ( arr , n , k ) ) ; } }