The question is:
Given N points(in 2D) with x and y coordinates, find a point P (in N given points) such that the sum of distances from other(N-1)
Step 1: Sort the points collection by x-dimension (nlogn)
Step 2: Calculate the x-distance between each point and all points TO THE LEFT of it:
xLDist[0] := 0
for i := 1 to n - 1
xLDist[i] := xLDist[i-1] + ( ( p[i].x - p[i-1].x ) * i)
Step 3: Calculate the x-distance between each point and all points TO THE RIGHT of it:
xRDist[n - 1] := 0
for i := n - 2 to 0
xRDist[i] := xRDist[i+1] + ( ( p[i+1].x - p[i].x ) * i)
Step 4: Sum both up you'll get the total x-distance from each point to the other N-1 points
for i := 0 to n - 1
p[i].xDist = xLDist[i] + xRDist[i]
Repeat Step 1,2,3,4 with the y-dimension to get
p[i].yDist
The point with the smallest sum of xDist and yDist is the answer
Total Complexity O(nlogn)
Answer in C++
Further explanation:
The idea is to reuse the already computed total distance of the previous point.
Lets say we have 3 point ABCD sorted, we see that the total left distance of D to the others before it are:
AD + BD + CD = (AC + CD) + (BC + CD) + CD = AC + BC + 3CD
In which (AC + BC) is the total left distance of C to the others before it, we took advantage of this and only need to compute ldist(C) + 3CD