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 . ; Driven Code
def distancesum ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE res = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT res += ( arr [ i ] * i - sum ) NEW_LINE sum += arr [ i ] NEW_LINE DEDENT return res NEW_LINE DEDENT def totaldistancesum ( x , y , n ) : NEW_LINE INDENT return distancesum ( x , n ) + distancesum ( y , n ) NEW_LINE DEDENT x = [ - 1 , 1 , 3 , 2 ] NEW_LINE y = [ 5 , 6 , 5 , 3 ] NEW_LINE n = len ( x ) NEW_LINE print ( totaldistancesum ( x , y , n ) ) NEW_LINE