Minimum Increment / decrement to make array elements equal | Function to return minimum operations need to be make each element of array equal ; Initialize cost to 0 ; Sort the array ; Middle element ; Find Cost ; If n , is even . Take minimum of the Cost obtained by considering both middle elements ; FInd cost again ; Take minimum of two cost ; Return total cost ; Driver code
def minCost ( A , n ) : NEW_LINE INDENT cost = 0 NEW_LINE A . sort ( ) ; NEW_LINE K = A [ int ( n / 2 ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT cost = cost + abs ( A [ i ] - K ) NEW_LINE DEDENT if n % 2 == 0 : NEW_LINE INDENT tempCost = 0 NEW_LINE K = A [ int ( n / 2 ) - 1 ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT tempCost = tempCost + abs ( A [ i ] - K ) NEW_LINE DEDENT cost = min ( cost , tempCost ) NEW_LINE DEDENT return cost NEW_LINE DEDENT A = [ 1 , 6 , 7 , 10 ] NEW_LINE n = len ( A ) NEW_LINE print ( minCost ( A , n ) ) NEW_LINE