Sum of Manhattan distances between all pairs of points | Return the sum of distance of one axis . ; sorting the array . ; for each point , finding the distance . ; Driver code
function distancesum ( arr , n ) { arr . sort ( ) ; let res = 0 , sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { res += ( arr [ i ] * i - sum ) ; sum += arr [ i ] ; } return res ; } function totaldistancesum ( x , y , n ) { return distancesum ( x , n ) + distancesum ( y , n ) ; } let x = [ - 1 , 1 , 3 , 2 ] ; let y = [ 5 , 6 , 5 , 3 ] ; let n = x . length ; document . write ( totaldistancesum ( x , y , n ) ) ;