![]() |
VOOZH | about |
Given an array arr[] consisting of N integer coordinates, the task is to find the maximum Manhattan Distance between any two distinct pairs of coordinates.
The Manhattan Distance between two points (X1, Y1) and (X2, Y2) is given by |X1 – X2| + |Y1 – Y2|.
Examples:
Input: arr[] = {(1, 2), (2, 3), (3, 4)}
Output: 4
Explanation:
The maximum Manhattan distance is found between (1, 2) and (3, 4) i.e., |3 - 1| + |4- 2 | = 4.Input: arr[] = {(-1, 2), (-4, 6), (3, -4), (-2, -4)}
Output: 17
Explanation:
The maximum Manhattan distance is found between (-4, 6) and (3, -4) i.e., |-4 - 3| + |6 - (-4)| = 17.
Naive Approach: The simplest approach is to iterate over the array, and for each coordinate, calculate its Manhattan distance from all remaining points. Keep updating the maximum distance obtained after each calculation. Finally, print the maximum distance obtained.
Below is the implementation of the above approach:
4
Time Complexity: O(N2), where N is the size of the given array.
Auxiliary Space: O(1)
Efficient Approach: The idea is to use store sums and differences between X and Y coordinates and find the answer by sorting those differences. Below are the observations to the above problem statement:
|Xi - Xj| + |Yi - Yj| = max(Xi - Xj -Yi + Yj,
-Xi + Xj + Yi - Yj,
-Xi + Xj - Yi + Yj,
Xi - Xj + Yi - Yj).
|Xi - Xj| + |Yi - Yj| = max((Xi - Yi) - (Xj - Yj),
(-Xi + Yi) - (-Xj + Yj),
(-Xi - Yi) - (-Xj - Yj),
(Xi + Yi) - (Xj + Yj))
Follow the below steps to solve the problem:
Below is the implementation of the above approach:
4
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Improving the Efficient Approach: Instead of storing the sums and differences in an auxiliary array, then sorting the arrays to determine the minimum and maximums, it is possible to keep a running total of the extreme sums and differences.
4
Time Complexity: O(N)
Auxiliary Space: O(1)
The ideas presented here are in two dimensions, but can be extended to further dimensions. Each additional dimension requires double the amount of computations on each point. For example, in 3-D space, the result is the maximum difference between the four extrema pairs computed from x+y+z, x+y-z, x-y+z, and x-y-z.