human
Can you provide a code to smallest positive integer K such that all array elements can be made equal by incrementing or decrementing by at most K and the other steps required given the following:
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"
How can the above be solved in Python?
assistant
#Here is code to smallest positive integer K such that all array elements can be made equal by incrementing or decrementing by at most K and the other steps required.
 def findMinKToMakeAllEqual ( N , A ) :
	B = { }
	for i in range ( N ) :
		B [ A [ i ] ] = 1
	M = len ( B )
	itr , i = list ( B . keys ( ) ) , 0
	if ( M > 3 ) :
		print ( " - 1" )
	elif ( M == 3 ) :
		B_1 , i = itr [ i ] , i + 1
		B_2 , i = itr [ i ] , i + 1
		B_3 , i = itr [ i ] , i + 1
		if ( B_2 - B_1 == B_3 - B_2 ) :
			print ( B_2 - B_1 )
		else :
			print ( " - 1" )
	elif ( M == 2 ) :
		B_1 , i = itr [ i ] , i + 1
		B_2 , i = itr [ i ] , i + 1
		if ( ( B_2 - B_1 ) % 2 == 0 ) :
			print ( ( B_2 - B_1 ) // 2 )
		else :
			print ( B_2 - B_1 )
	else :
		print ( 0 )
if __name__ == ' _ _ main _ _ ' :
	A = [ 1 , 3 , 5 , 1 ]
	N = len ( A )
	findMinKToMakeAllEqual ( N , A )