Minimize the maximum difference of any pair by doubling odd elements and reducing even elements by half | Function to minimize the maximum difference between any pair of elements of the array by the given operations ; Traverse the array ; If current element is even ; Insert it into even ; Otherwise ; Make it even by multiplying by 2 and insert it into set ; Calculate difference between first and the last element of the set ; Iterate until difference is minimized ; Erase the current element ; Reduce current element by half and insert it into the Set ; Update difference ; Return the resultant difference ; Driver Code
def minimumMaxDiff ( nums ) : NEW_LINE INDENT s = { } NEW_LINE for i in range ( len ( nums ) ) : NEW_LINE INDENT if ( nums [ i ] % 2 == 0 ) : NEW_LINE INDENT s [ nums [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT s [ nums [ i ] * 2 ] = 1 NEW_LINE DEDENT DEDENT sr = list ( s . keys ( ) ) NEW_LINE res = sr [ - 1 ] - sr [ 0 ] NEW_LINE while ( list ( s . keys ( ) ) [ - 1 ] % 2 == 0 ) : NEW_LINE INDENT r = list ( s . keys ( ) ) NEW_LINE x = r [ - 1 ] NEW_LINE del s [ x ] NEW_LINE s [ x // 2 ] = 1 NEW_LINE rr = list ( s . keys ( ) ) NEW_LINE res = min ( res , rr [ - 1 ] - r [ 0 ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 9 ] NEW_LINE print ( minimumMaxDiff ( arr ) ) NEW_LINE DEDENT