Array element with minimum sum of absolute differences | Function to return the minimized sum ; Sort the array ; Median of the array ; Calculate the minimized sum ; Return the required sum ; Driver code
function minSum ( arr , n ) { arr . sort ( ) ; let x = arr [ Math . floor ( n / 2 ) ] ; let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) sum += Math . abs ( arr [ i ] - x ) ; return sum ; } let arr = [ 1 , 3 , 9 , 3 , 6 ] ; let n = arr . length ; document . write ( minSum ( arr , n ) ) ;