# Maximum Manhattan distance between a distinct pair from N coordinates

• Difficulty Level : Medium
• Last Updated : 04 Jan, 2023

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:

## C++

 // C++ program for the above approach #include using namespace std; // Function to calculate the maximum// Manhattan distancevoid MaxDist(vector >& A, int N){    // Stores the maximum distance    int maximum = INT_MIN;     for (int i = 0; i < N; i++) {         int sum = 0;         for (int j = i + 1; j < N; j++) {             // Find Manhattan distance            // using the formula            // |x1 - x2| + |y1 - y2|            sum = abs(A[i].first - A[j].first)                  + abs(A[i].second - A[j].second);             // Updating the maximum            maximum = max(maximum, sum);        }    }     cout << maximum;} // Driver Codeint main(){    int N = 3;     // Given Co-ordinates    vector > A        = { { 1, 2 }, { 2, 3 }, { 3, 4 } };     // Function Call    MaxDist(A, N);     return 0;}

## Java

 // Java program for the above approachimport java.io.*;import java.util.*; class GFG {     // Pair class    public static class Pair {        int x;        int y;         Pair(int x, int y)        {            this.x = x;            this.y = y;        }    }     // Function to calculate the maximum    // Manhattan distance    static void MaxDist(ArrayList A, int N)    {         // Stores the maximum distance        int maximum = Integer.MIN_VALUE;         for (int i = 0; i < N; i++) {            int sum = 0;             for (int j = i + 1; j < N; j++) {                 // Find Manhattan distance                // using the formula                // |x1 - x2| + |y1 - y2|                sum = Math.abs(A.get(i).x - A.get(j).x)                      + Math.abs(A.get(i).y - A.get(j).y);                 // Updating the maximum                maximum = Math.max(maximum, sum);            }        }        System.out.println(maximum);    }     // Driver Code    public static void main(String[] args)    {        int n = 3;         ArrayList al = new ArrayList<>();         // Given Co-ordinates        Pair p1 = new Pair(1, 2);        al.add(p1);         Pair p2 = new Pair(2, 3);        al.add(p2);         Pair p3 = new Pair(3, 4);        al.add(p3);         // Function call        MaxDist(al, n);    }} // This code is contributed by bikram2001jha

## Python3

 # Python3 program for the above approachimport sys # Function to calculate the maximum# Manhattan distance  def MaxDist(A, N):     # Stores the maximum distance    maximum = - sys.maxsize     for i in range(N):        sum = 0         for j in range(i + 1, N):             # Find Manhattan distance            # using the formula            # |x1 - x2| + |y1 - y2|            Sum = (abs(A[i][0] - A[j][0]) +                   abs(A[i][1] - A[j][1]))             # Updating the maximum            maximum = max(maximum, Sum)     print(maximum)  # Driver codeN = 3 # Given co-ordinatesA = [[1, 2], [2, 3], [3, 4]] # Function callMaxDist(A, N) # This code is contributed by divyeshrabadiya07

## C#

 // C# program for the above approachusing System;using System.Collections.Generic; class GFG {     // Pair class    public class Pair {        public int x;        public int y;         public Pair(int x, int y)        {            this.x = x;            this.y = y;        }    }     // Function to calculate the maximum    // Manhattan distance    static void MaxDist(List A, int N)    {         // Stores the maximum distance        int maximum = int.MinValue;         for (int i = 0; i < N; i++) {            int sum = 0;             for (int j = i + 1; j < N; j++) {                 // Find Manhattan distance                // using the formula                // |x1 - x2| + |y1 - y2|                sum = Math.Abs(A[i].x - A[j].x)                      + Math.Abs(A[i].y - A[j].y);                 // Updating the maximum                maximum = Math.Max(maximum, sum);            }        }        Console.WriteLine(maximum);    }     // Driver Code    public static void Main(String[] args)    {        int n = 3;         List al = new List();         // Given Co-ordinates        Pair p1 = new Pair(1, 2);        al.Add(p1);         Pair p2 = new Pair(2, 3);        al.Add(p2);         Pair p3 = new Pair(3, 4);        al.Add(p3);         // Function call        MaxDist(al, n);    }} // This code is contributed by Amit Katiyar

## Javascript



Output

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:

• Manhattan Distance between any two points (Xi, Yi) and (Xj, Yj) can be written as follows:

|Xi – Xj| + |Yi – Yj| = max(Xi – Xj -Yi + Yj
-Xi + Xj + Yi – Yj
-Xi + Xj – Yi + Yj
Xi – Xj + Yi – Yj).

• The above expression can be rearranged as:

|Xi – Xj| + |Yi – Yj| = max((Xi – Yi) – (Xj – Yj),
(-Xi + Yi) – (-Xj + Yj),
(-Xi – Yi) – (-Xj – Yj),
(Xi + Yi) – (Xj + Yj))

• It can be observed from the above expression, that the answer can be found by storing the sum and differences of the coordinates.

Follow the below steps to solve the problem:

1. Initialize two arrays sum[] and diff[].
2. Store the sum of X and Y coordinates i.e., Xi + Yi in sum[] and their difference i.e., Xi – Yi in diff[].
3. Sort the sum[] and diff[] in ascending order.
4. The maximum of the values (sum[N-1] – sum[0]) and (diff[N-1] – diff[0]) is the required result.

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach #include using namespace std; // Function to calculate the maximum// Manhattan distancevoid MaxDist(vector >& A, int N){    // Vectors to store maximum and    // minimum of all the four forms    vector V(N), V1(N);     for (int i = 0; i < N; i++) {        V[i] = A[i].first + A[i].second;        V1[i] = A[i].first - A[i].second;    }     // Sorting both the vectors    sort(V.begin(), V.end());    sort(V1.begin(), V1.end());     int maximum        = max(V.back() - V.front(), V1.back() - V1.front());     cout << maximum << endl;} // Driver Codeint main(){    int N = 3;     // Given Co-ordinates    vector > A        = { { 1, 2 }, { 2, 3 }, { 3, 4 } };     // Function Call    MaxDist(A, N);     return 0;}

## Java

 // Java program for the above approachimport java.io.*;import java.util.*; class GFG {     // Pair class    public static class Pair {        int x;        int y;         Pair(int x, int y)        {            this.x = x;            this.y = y;        }    }     // Function to calculate the maximum    // Manhattan distance    static void MaxDist(ArrayList A, int N)    {         // ArrayLists to store maximum and        // minimum of all the four forms        ArrayList V = new ArrayList<>();        ArrayList V1 = new ArrayList<>();         for (int i = 0; i < N; i++) {            V.add(A.get(i).x + A.get(i).y);            V1.add(A.get(i).x - A.get(i).y);        }         // Sorting both the ArrayLists        Collections.sort(V);        Collections.sort(V1);         int maximum            = Math.max((V.get(V.size() - 1) - V.get(0)),                       (V1.get(V1.size() - 1) - V1.get(0)));         System.out.println(maximum);    }     // Driver Code    public static void main(String[] args)    {        int n = 3;         ArrayList al = new ArrayList<>();         // Given Co-ordinates        Pair p1 = new Pair(1, 2);        al.add(p1);        Pair p2 = new Pair(2, 3);        al.add(p2);        Pair p3 = new Pair(3, 4);        al.add(p3);         // Function call        MaxDist(al, n);    }} // This code is contributed by bikram2001jha

## Python3

 # Python3 program for the above approach # Function to calculate the maximum# Manhattan distance  def MaxDist(A, N):     # List to store maximum and    # minimum of all the four forms    V = [0 for i in range(N)]    V1 = [0 for i in range(N)]     for i in range(N):        V[i] = A[i][0] + A[i][1]        V1[i] = A[i][0] - A[i][1]     # Sorting both the vectors    V.sort()    V1.sort()     maximum = max(V[-1] - V[0],                  V1[-1] - V1[0])     print(maximum)  # Driver codeif __name__ == "__main__":     N = 3     # Given Co-ordinates    A = [[1, 2],         [2, 3],         [3, 4]]     # Function call    MaxDist(A, N) # This code is contributed by rutvik_56

## C#

 // C# program for the above approachusing System;using System.Collections.Generic; class GFG {     // Pair class    class Pair {        public int x;        public int y;         public Pair(int x, int y)        {            this.x = x;            this.y = y;        }    }     // Function to calculate the maximum    // Manhattan distance    static void MaxDist(List A, int N)    {         // Lists to store maximum and        // minimum of all the four forms        List V = new List();        List V1 = new List();         for (int i = 0; i < N; i++) {            V.Add(A[i].x + A[i].y);            V1.Add(A[i].x - A[i].y);        }         // Sorting both the Lists        V.Sort();        V1.Sort();         int maximum = Math.Max((V[V.Count - 1] - V[0]),                               (V1[V1.Count - 1] - V1[0]));         Console.WriteLine(maximum);    }     // Driver Code    public static void Main(String[] args)    {        int n = 3;         List al = new List();         // Given Co-ordinates        Pair p1 = new Pair(1, 2);        al.Add(p1);        Pair p2 = new Pair(2, 3);        al.Add(p2);        Pair p3 = new Pair(3, 4);        al.Add(p3);         // Function call        MaxDist(al, n);    }} // This code is contributed by Amit Katiyar

## Javascript



Output

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.

## C++

 // C++ program for the above approach #include using namespace std; // Function to calculate the maximum// Manhattan distancevoid MaxDist(vector >& A, int N){    // Variables to track running extrema    int minsum, maxsum, mindiff, maxdiff;     minsum = maxsum = A[0].first + A[0].second;    mindiff = maxdiff = A[0].first - A[0].second;    for (int i = 1; i < N; i++) {        int sum = A[i].first + A[i].second;        int diff = A[i].first - A[i].second;        if (sum < minsum)            minsum = sum;        else if (sum > maxsum)            maxsum = sum;        if (diff < mindiff)            mindiff = diff;        else if (diff > maxdiff)            maxdiff = diff;    }     int maximum = max(maxsum - minsum, maxdiff - mindiff);     cout << maximum << endl;} // Driver Codeint main(){    int N = 3;     // Given Co-ordinates    vector > A        = { { 1, 2 }, { 2, 3 }, { 3, 4 } };     // Function Call    MaxDist(A, N);     return 0;}

## Java

 // Java program for the above approachpublic class GFG {     // Function to calculate the maximum    // Manhattan distance    static void MaxDist(int[][] A, int N)    {        // Variables to track running extrema        int minsum, maxsum, mindiff, maxdiff;         minsum = maxsum = A[0][0] + A[0][1];        mindiff = maxdiff = A[0][0] - A[0][1];        for (int i = 1; i < N; i++) {            int sum = A[i][0] + A[i][1];            int diff = A[i][0] - A[i][1];            if (sum < minsum)                minsum = sum;            else if (sum > maxsum)                maxsum = sum;            if (diff < mindiff)                mindiff = diff;            else if (diff > maxdiff)                maxdiff = diff;        }         int maximum            = Math.max(maxsum - minsum, maxdiff - mindiff);         System.out.println(maximum);    }     // Driver Code    public static void main(String[] args)    {        int N = 3;         // Given Co-ordinates        int[][] A = { { 1, 2 }, { 2, 3 }, { 3, 4 } };         // Function Call        MaxDist(A, N);    }} // The code is contributed by Gautam goel (gautamgoel962)

## Python3

 # Python program for the above approach # Function to calculate the maximum# Manhattan distancedef MaxDist(A, N):     # Variables to track running extrema    minsum = maxsum = A[0][0] + A[0][1]    mindiff = maxdiff = A[0][0] - A[0][1]     for i in range(1,N):        sum = A[i][0] + A[i][1]        diff = A[i][0] - A[i][1]        if (sum < minsum):            minsum = sum        elif (sum > maxsum):            maxsum = sum        if (diff < mindiff):            mindiff = diff        elif (diff > maxdiff):            maxdiff = diff     maximum = max(maxsum - minsum, maxdiff - mindiff)     print(maximum) # Driver CodeN = 3 # Given Co-ordinatesA = [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ] ] # Function CallMaxDist(A, N) # This code is contributed by shinjanpatra

## C#

 // Include namespace systemusing System; // C# program for the above approachpublic class GFG{  // Function to calculate the maximum  // Manhattan distance  public static void MaxDist(int[,] A, int N)  {         // Variables to track running extrema    int minsum;    int maxsum;    int mindiff;    int maxdiff;    minsum = maxsum = A[0,0] + A[0,1];    mindiff = maxdiff = A[0,0] - A[0,1];    for (int i = 1; i < N; i++)    {      var sum = A[i,0] + A[i,1];      var diff = A[i,0] - A[i,1];      if (sum < minsum)      {        minsum = sum;      }      else if (sum > maxsum)      {        maxsum = sum;      }      if (diff < mindiff)      {        mindiff = diff;      }      else if (diff > maxdiff)      {        maxdiff = diff;      }    }    var maximum = Math.Max(maxsum - minsum,maxdiff - mindiff);    Console.WriteLine(maximum);  }     // Driver Code  public static void Main(String[] args)  {    var N = 3;         // Given Co-ordinates    int[,] A = {{1, 2}, {2, 3}, {3, 4}};         // Function Call    GFG.MaxDist(A, N);  }}

## Javascript



Output

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.

My Personal Notes arrow_drop_up