human
Write me a code to minimum increment operations to make K elements equal and the other steps required given the following:
Minimum increment operations to make K elements equal | Function to return the minimum number of increment operations required to make any k elements of the array equal.
Sort the array in increasing order.
Calculate the number of operations needed to make 1 st k elements equal to the kth element i . e . the 1 st window.
Answer will be the minimum of all possible k sized windows.
Find the operations needed to make k elements equal to ith element.
Slide the window to the right and subtract increments spent on leftmost element of the previous window.
Add increments needed to make the 1 st k - 1 elements of this window equal to the kth element of the current window.
Driver code"
Solution in Python:
assistant
#Here is code to minimum increment operations to make K elements equal and the other steps required.
 def minOperations ( ar , k ) :
	ar = sorted ( ar )
	opsNeeded = 0
	for i in range ( k ) :
		opsNeeded += ar [ k - 1 ] - ar [ i ]
	ans = opsNeeded
	for i in range ( k , len ( ar ) ) :
		opsNeeded = opsNeeded - ( ar [ i - 1 ] - ar [ i - k ] )
		opsNeeded += ( k - 1 ) * ( ar [ i ] - ar [ i - 1 ] )
		ans = min ( ans , opsNeeded )
	return ans
arr = [ 3 , 1 , 9 , 100 ]
n = len ( arr )
k = 3
print ( minOperations ( arr , k ) )