Minimum value of X to make all array elements equal by either decreasing or increasing by X | Function that returns the minimum value of X ; Declare a set ; Iterate in the array element and insert them into the set ; If unique elements is 1 ; Unique elements is 2 ; Get both el2 and el1 ; Check if they are even ; If there are 3 unique elements ; Get three unique elements ; Check if their difference is same ; More than 3 unique elements ; Driver code
def findMinimumX ( a , n ) : NEW_LINE INDENT st = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT st . add ( a [ i ] ) NEW_LINE DEDENT if ( len ( st ) == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( len ( st ) == 2 ) : NEW_LINE INDENT st = list ( st ) NEW_LINE el1 = st [ 0 ] NEW_LINE el2 = st [ 1 ] NEW_LINE if ( ( el2 - el1 ) % 2 == 0 ) : NEW_LINE INDENT return int ( ( el2 - el1 ) / 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( el2 - el1 ) NEW_LINE DEDENT DEDENT if ( len ( st ) == 3 ) : NEW_LINE INDENT st = list ( st ) NEW_LINE el1 = st [ 0 ] NEW_LINE el2 = st [ 1 ] NEW_LINE el3 = st [ 2 ] NEW_LINE if ( ( el2 - el1 ) == ( el3 - el2 ) ) : NEW_LINE INDENT return el2 - el1 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 4 , 4 , 7 , 4 , 1 ] NEW_LINE n = len ( a ) NEW_LINE print ( findMinimumX ( a , n ) ) NEW_LINE DEDENT