Smallest positive integer K such that all array elements can be made equal by incrementing or decrementing by at most K | Function to find smallest integer K such that incrementing or decrementing each element by K at most once makes all elements equal ; Store distinct array elements ; Traverse the array , A [ ] ; Count elements into the set ; Iterator to store first element of B ; If M is greater than 3 ; If M is equal to 3 ; Stores the first smallest element ; Stores the second smallest element ; Stores the largest element ; IF difference between B_2 and B_1 is equal to B_3 and B_2 ; If M is equal to 2 ; Stores the smallest element ; Stores the largest element ; If difference is an even ; If M is equal to 1 ; Driver Code ; Given array ; Given size ; Print the required smallest integer
def findMinKToMakeAllEqual ( N , A ) : NEW_LINE INDENT B = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT B [ A [ i ] ] = 1 NEW_LINE DEDENT M = len ( B ) NEW_LINE itr , i = list ( B . keys ( ) ) , 0 NEW_LINE if ( M > 3 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT elif ( M == 3 ) : NEW_LINE INDENT B_1 , i = itr [ i ] , i + 1 NEW_LINE B_2 , i = itr [ i ] , i + 1 NEW_LINE B_3 , i = itr [ i ] , i + 1 NEW_LINE if ( B_2 - B_1 == B_3 - B_2 ) : NEW_LINE INDENT print ( B_2 - B_1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT elif ( M == 2 ) : NEW_LINE INDENT B_1 , i = itr [ i ] , i + 1 NEW_LINE B_2 , i = itr [ i ] , i + 1 NEW_LINE if ( ( B_2 - B_1 ) % 2 == 0 ) : NEW_LINE INDENT print ( ( B_2 - B_1 ) // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( B_2 - B_1 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 3 , 5 , 1 ] NEW_LINE N = len ( A ) NEW_LINE findMinKToMakeAllEqual ( N , A ) NEW_LINE DEDENT