Make all array elements equal with minimum cost | This function assumes that a [ ] is sorted . If a [ ] is not sorted , we need to sort it first . ; If there are odd elements , we choose middle element ; If there are even elements , then we choose the average of middle two . ; After deciding the final value , find the result . ; Driver program
function minCostToMakeElementEqual ( a , n ) { let y ; if ( n % 2 == 1 ) y = a [ Math . trunc ( n / 2 ) ] ; else y = Math . trunc ( ( a [ n / 2 ] + a [ ( n - 2 ) / 2 ] ) / 2 ) ; let s = 0 ; for ( let i = 0 ; i < n ; i ++ ) s += Math . abs ( a [ i ] - y ) ; return s ; } let a = [ 1 , 100 , 101 ] ; let n = a . length ; document . write ( minCostToMakeElementEqual ( a , n ) ) ;