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
function minCost ( A , n ) { var cost = 0 ; A . sort ( ) ; var K = A [ parseInt ( n / 2 ) ] ; var i ; for ( i = 0 ; i < n ; ++ i ) cost += Math . abs ( A [ i ] - K ) ; if ( n % 2 == 0 ) { var tempCost = 0 ; K = A [ parseInt ( n / 2 ) - 1 ] ; for ( i = 0 ; i < n ; ++ i ) tempCost += Math . abs ( A [ i ] - K ) ; cost = Math . min ( cost , tempCost ) ; } return cost ; } var A = [ 1 , 6 , 7 , 10 ] ; var n = A . length ; document . write ( minCost ( A , n ) ) ;