Given a set of points on a 2D plane, the greatest Manhattan distance between any two points can be found in 1 pass, linear time, and constant space.
Time Complexity:O(N), where N is the number of points
Space Complexity:O(1)
Code
Given:
points: List[List[int]]
min_sum =float('inf')
max_sum =float('-inf')
min_diff =float('inf')
max_diff =float('-inf')# If you are not interested in the points themselves, you can remove these variables
min_sum_i =-1
max_sum_i =-1
min_diff_i =-1
max_diff_i =-1for i inrange(len(points)):
x, y = points[i]if x + y > max_sum:
max_sum = x + y
max_sum_i = i
if x + y < min_sum:
min_sum = x + y
min_sum_i = i
if x - y > max_diff:
max_diff = x - y
max_diff_i = i
if x - y < min_diff:
min_diff = x - y
min_diff_i = i
if max_sum - min_sum > max_diff - min_diff:# Points indices = [max_sum_i, min_sum_i]return max_sum - min_sum
else:# Points indices = [max_diff_i, min_diff_i]return max_diff - min_diff
Explanation
The formula for Manhattan distance is:
Manhattan(Pi,Pj)=∣xi−xj∣+∣yi−yj∣
First, let's remove the absolute value bars from the formula. This will give us the following four equations:
=⎩⎨⎧xi−xj+yi−yjxi−xj−yi+yj−xi+xj+yi−yj−xi+xj−yi+yjif xi≥xj and yi≥yjif xi≥xj and yi<yjif xi<xj and yi≥yjif xi<xj and yi<yj
Now, we will group together the corresponding X and Y values for each point:
=⎩⎨⎧xi+yi−xj−yjxi−yi−xj+yj−xi+yi+xj−yj−xi−yi+xj+yjif xi≥xj and yi≥yjif xi≥xj and yi<yjif xi<xj and yi≥yjif xi<xj and yi<yj
Pull out some minus signs:
=⎩⎨⎧(xi+yi)−(xj+yj)(xi−yi)−(xj−yj)−(xi−yi)+(xj−yj)−(xi+yi)+(xj+yj)if xi≥xj and yi≥yjif xi≥xj and yi<yjif xi<xj and yi≥yjif xi<xj and yi<yj
We can define two variables as follows:
sumi=si=xi+yidiffi=di=xi−yi
And rewrite our equations:
=⎩⎨⎧si−sjdi−dj−di+dj−si+sjif xi≥xj and yi≥yjif xi≥xj and yi<yjif xi<xj and yi≥yjif xi<xj and yi<yj
Notice that which point is 'i' and which is 'j' is arbitrary, since we are only interested in the specific i and j combination resulting in the greatest distance.
Therefore, -si + sj is functionally equivalent to si - sj.
This means that we are just interested in finding the maximum of:
In order to maximize these values, we need the largest si and di, and the smallest sj and dj. This is why we use 4 variables to track the max and min x + y and x - y in the code.