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
< ? php function minCost ( $ A , $ n ) { $ cost = 0 ; sort ( $ A ) ; $ K = $ A [ $ n / 2 ] ; for ( $ i = 0 ; $ i < $ n ; ++ $ i ) $ cost += abs ( $ A [ $ i ] - $ K ) ; if ( $ n % 2 == 0 ) { $ tempCost = 0 ; $ K = $ A [ ( $ n / 2 ) - 1 ] ; for ( $ i = 0 ; $ i < $ n ; ++ $ i ) $ tempCost += abs ( $ A [ $ i ] - $ K ) ; $ cost = min ( $ cost , $ tempCost ) ; } return $ cost ; } $ A = array ( 1 , 6 , 7 , 10 ) ; $ n = sizeof ( $ A ) ; echo minCost ( $ A , $ n ) ; ? >