Minimum Cost to make all array elements equal using given operations | javascript implementation to find the minimum cost to make all array elements equal ; Checks if the value is less than middle element of the array ; Function that returns the cost of making all elements equal to current element ; Compute the lower bound of current element ; Calculate the requirement of add operation ; Calculate the requirement of subtract operation ; Compute minimum of left and right ; Computing the total cost of add and subtract operations ; Function that prints minimum cost of making all elements equal ; Sort the given array ; Calculate minimum from a + r and m ; Compute prefix sum and store in pref array ; Find the minimum cost from the given elements ; Finding the minimum cost from the other cases where minimum cost can occur ; Printing the minimum cost of making all elements equal ; Driver Code ; Function Call
function lowerBound ( array , length , value ) { var low = 0 ; var high = length ; while ( low < high ) { var mid = parseInt ( ( low + high ) / 2 ) ; if ( value <= array [ mid ] ) { high = mid ; } else { low = mid + 1 ; } } return low ; } function costCalculation ( current , arr , n , pref , a , r , minimum ) { var index = lowerBound ( arr , arr . length , current ) ; var left = index * current - pref [ index ] ; var right = pref [ n ] - pref [ index ] - ( n - index ) * current ; var res = Math . min ( left , right ) ; left -= res ; right -= res ; var total = res * minimum ; total += left * a ; total += right * r ; return total ; } function solve ( arr , n , a , r , m ) { arr . sort ( ) ; var minimum = Math . min ( a + r , m ) ; var pref = Array ( n + 1 ) . fill ( 0 ) ; for ( i = 0 ; i < n ; i ++ ) pref [ i + 1 ] = pref [ i ] + arr [ i ] ; var ans = 10000 ; for ( i = 0 ; i < n ; i ++ ) ans = Math . min ( ans , costCalculation ( arr [ i ] , arr , n , pref , a , r , minimum ) ) ; ans = Math . min ( ans , costCalculation ( pref [ n ] / n , arr , n , pref , a , r , minimum ) ) ; ans = Math . min ( ans , costCalculation ( pref [ n ] / n + 1 , arr , n , pref , a , r , minimum ) ) ; document . write ( ans ) ; } var arr = [ 5 , 5 , 3 , 6 , 5 ] ; var A = 1 , R = 2 , M = 4 ; var size = arr . length ; solve ( arr , size , A , R , M ) ;