Maximum Manhattan distance between a distinct pair from N coordinates

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the maximum
// Manhattan distance
void MaxDist(
    vector<pair<int, int> >& 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 Code
int main()
{
    int N = 3;
 
    // Given Co-ordinates
    vector<pair<int, int> > A
        = { { 1, 2 }, { 2, 3 }, { 3, 4 } };
 
    // Function Call
    MaxDist(A, N);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import 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<Pair> 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<Pair> 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
import 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 code
N = 3
 
# Given co-ordinates
A = [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ] ]
 
# Function call
MaxDist(A, N)
 
# This code is contributed by divyeshrabadiya07

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using 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<Pair> 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<Pair> al = new List<Pair>();
     
    // 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

chevron_right


Output: 

4









 

Time Complexity: O(N2), where N is the size of the given array.
Auxiliary Space: O(N)

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the maximum
// Manhattan distance
void MaxDist(
    vector<pair<int, int> >& A, int N)
{
    // Vectors to store maximum and
    // minimum of all the four forms
    vector<int> 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 Code
int main()
{
    int N = 3;
 
    // Given Co-ordinates
    vector<pair<int, int> > A
        = { { 1, 2 }, { 2, 3 }, { 3, 4 } };
 
    // Function Call
    MaxDist(A, N);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import 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<Pair> A, int N)
{
     
    // ArrayLists to store maximum and
    // minimum of all the four forms
    ArrayList<Integer> V = new ArrayList<>();
    ArrayList<Integer> 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<Pair> 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 code   
if __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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using 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<Pair> A, int N)
{
     
    // Lists to store maximum and
    // minimum of all the four forms
    List<int> V = new List<int>();
    List<int> V1 = new List<int>();
     
    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<Pair> al = new List<Pair>();
     
    // 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

chevron_right


Output: 

4









 

Time Complexity: O(N*log N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.