Minimize deviation of an array by given operations | Function to find the minimum deviation of the array A [ ] ; Store all array elements in sorted order ; Odd number are transformed using 2 nd operation ; ( Maximum - Minimum ) ; Check if the size of set is > 0 and the maximum element is divisible by 2 ; Maximum element of the set ; Erase the maximum element ; Using operation 1 ; ( Maximum - Minimum ) ; Print the Minimum Deviation Obtained ; Driver Code ; Function Call to find Minimum Deviation of A [ ]
def minimumDeviation ( A , N ) : NEW_LINE INDENT s = set ( [ ] ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] % 2 == 0 ) : NEW_LINE INDENT s . add ( A [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT s . add ( 2 * A [ i ] ) NEW_LINE DEDENT DEDENT s = list ( s ) NEW_LINE diff = s [ - 1 ] - s [ 0 ] NEW_LINE while ( len ( s ) and s [ - 1 ] % 2 == 0 ) : NEW_LINE INDENT maxEl = s [ - 1 ] NEW_LINE s . remove ( maxEl ) NEW_LINE s . append ( maxEl // 2 ) NEW_LINE diff = min ( diff , s [ - 1 ] - s [ 0 ] ) NEW_LINE DEDENT print ( diff ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 4 , 1 , 5 , 20 , 3 ] NEW_LINE N = len ( A ) NEW_LINE minimumDeviation ( A , N ) NEW_LINE DEDENT