Minimize the difference between minimum and maximum elements | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimizeDiff ( int * arr , int n , int k ) { int max = * ( max_element ( arr , arr + n ) ) ; int min = * ( min_element ( arr , arr + n ) ) ; 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 = * ( max_element ( arr , arr + n ) ) ; min = * ( min_element ( arr , arr + n ) ) ; return ( max - min ) ; } int main ( ) { int arr [ ] = { 3 , 16 , 12 , 9 , 20 } ; int n = 5 ; int k = 3 ; cout << " Max ▁ height ▁ difference ▁ = ▁ " << minimizeDiff ( arr , n , k ) << endl ; return 0 ; }