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
def minimizeDiff ( arr , n , k ) : NEW_LINE INDENT max_element = max ( arr ) NEW_LINE min_element = min ( arr ) NEW_LINE if ( ( max_element - min_element ) <= k ) : NEW_LINE INDENT return ( max_element - min_element ) NEW_LINE DEDENT avg = ( max_element + min_element ) // 2 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > avg ) : NEW_LINE INDENT arr [ i ] -= k NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] += k NEW_LINE DEDENT DEDENT max_element = max ( arr ) NEW_LINE min_element = min ( arr ) NEW_LINE return ( max_element - min_element ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 16 , 12 , 9 , 20 ] NEW_LINE n = 5 NEW_LINE k = 3 NEW_LINE print ( " Max ▁ height ▁ difference ▁ = " , minimizeDiff ( arr , n , k ) ) NEW_LINE DEDENT