The Wayback Machine - https://web.archive.org/web/20240704000451/https://www.geeksforgeeks.org/maximum-manhattan-distance-between-a-distinct-pair-from-n-coordinates/
Open In App

Maximum Manhattan distance between a distinct pair from N coordinates

Last Updated : 04 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 <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;
}


Java




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


Python3




# 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


C#




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


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to calculate the maximum
// Manhattan distance
function MaxDist(A, N){
 
    // Stores the maximum distance
    let maximum = Number.MIN_VALUE
    for(let i = 0; i < N; i++)
    {
        let Sum = 0
 
        for(let j = i + 1; j < N; j++)
        {
 
            // Find Manhattan distance
            // using the formula
            // |x1 - x2| + |y1 - y2|
            Sum = (Math.abs(A[i][0] - A[j][0]) +
                   Math.abs(A[i][1] - A[j][1]))
 
            // Updating the maximum
            maximum = Math.max(maximum, Sum)
        }
    }
 
    document.write(maximum)
}
 
 
// Driver code
let N = 3
 
// Given co-ordinates
let A = [[1, 2], [2, 3], [3, 4]]
 
// Function call
MaxDist(A, N)
 
// This code is contributed by shinjanpatra
 
</script>


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 <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;
}


Java




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


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


C#




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


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to calculate the maximum
// Manhattan distance
function MaxDist(A, N)
{
 
    // List to store maximum and
    // minimum of all the four forms
    let V = new Array(N).fill(0)
    let V1 = new Array(N).fill(0)
 
    for(let i = 0; i < N; i++){
        V[i] = A[i][0] + A[i][1]
        V1[i] = A[i][0] - A[i][1]
    }
 
    // Sorting both the vectors
    V.sort()
    V1.sort()
 
    let maximum = Math.max(V[V.length-1] - V[0],
                  V1[V1.length-1] - V1[0])
 
    document.write(maximum,"</br>")
}
 
// Driver code
let N = 3
 
// Given Co-ordinates
let A = [[1, 2],
         [2, 3],
         [3, 4]]
 
// Function call
MaxDist(A, N)
 
// This code is contributed by shinjanpatra
 
</script>


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 <bits/stdc++.h>
using namespace std;
 
// Function to calculate the maximum
// Manhattan distance
void MaxDist(vector<pair<int, int> >& 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 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;
}


Java




// Java program for the above approach
public 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 distance
def 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 Code
N = 3
 
# Given Co-ordinates
A = [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ] ]
 
# Function Call
MaxDist(A, N)
 
# This code is contributed by shinjanpatra


C#




// Include namespace system
using System;
 
// C# program for the above approach
public 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




<script>
 
// JavaScript program for the above approach
 
 
// Function to calculate the maximum
// Manhattan distance
function MaxDist(A, N)
{
    // Variables to track running extrema
    let minsum, maxsum, mindiff, maxdiff;
 
    minsum = maxsum = A[0][0] + A[0][1];
    mindiff = maxdiff = A[0][0] - A[0][1];
    for (let i = 1; i < N; i++) {
        let sum = A[i][0] + A[i][1];
        let 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;
    }
 
    let maximum = Math.max(maxsum - minsum, maxdiff - mindiff);
 
    document.write(maximum,"</br>");
}
 
// Driver Code
 
let N = 3;
 
// Given Co-ordinates
let A = [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ] ];
 
// Function Call
MaxDist(A, N);
 
// code is contributed by shinjanpatra
 
</script>


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.



Similar Reads

Minimum Manhattan distance covered by visiting every coordinates from a source to a final vertex
Given an array arr[] of co-ordinate points and a source and final co-ordinate point, the task is to find the minimum manhattan distance covered from the source to the final vertex such that every point of the array is visited exactly once. Manhattan Distance = [Tex]\left | x2 - x1 \right | + \left | y2 - y1 \right | [/Tex] Examples: Input: source =
11 min read
Find 4 points with equal Manhattan distance between any pair
Given an integer N, Find 4 points in a 2D plane having integral coordinates, such that the Manhattan distance between any pair of points is equal to N. Examples: Input: N = 6Output: { {0, -3}, {3, 0}, {-3, 0}, {0, 3} }Explanation: It can be easily calculated that Manhattan distance between all possible pairs is 6. Input: N = 11Output: -1Explanation
7 min read
Count paths with distance equal to Manhattan distance
Given two points (x1, y1) and (x2, y2) in 2-D coordinate system. The task is to count all the paths whose distance is equal to the Manhattan distance between both the given points.Examples: Input: x1 = 2, y1 = 3, x2 = 4, y2 = 5 Output: 6Input: x1 = 2, y1 = 6, x2 = 4, y2 = 9 Output: 10 Approach: The Manhattan distance between the points (x1, y1) and
7 min read
Find the original coordinates whose Manhattan distances are given
Given the Manhattan distances of three coordinates on a 2-D plane, the task is to find the original coordinates. Print any solution if multiple solutions are possible else print -1. Input: d1 = 3, d2 = 4, d3 = 5 Output: (0, 0), (3, 0) and (1, 3) Manhattan distance between (0, 0) to (3, 0) is 3, (3, 0) to (1, 3) is 5 and (0, 0) to (1, 3) is 4Input:
6 min read
Calculate the Manhattan Distance between two cells of given 2D array
Given a 2D array of size M * N and two points in the form (X1, Y1) and (X2 , Y2) where X1 and X2 represents the rows and Y1 and Y2 represents the column. The task is to calculate the Manhattan distance between the given points. Examples: Input: M = 5, N = 5, X1 = 1, Y1 = 2, X2 = 3, Y2 = 3Output: 3Explanation: As per the definition, the Manhattan th
4 min read
Find the integer points (x, y) with Manhattan distance atleast N
Given a number N, the task is to find the integer points (x, y) such that 0 &lt;= x, y &lt;= N and Manhattan distance between any two points will be atleast N.Examples: Input: N = 3 Output: (0, 0) (0, 3) (3, 0) (3, 3) Input: N = 4 Output: (0, 0) (0, 4) (4, 0) (4, 4) (2, 2) Approach: Manhattan Distance between two points (x1, y1) and (x2, y2) is: |x
6 min read
Check if any point exists in a plane whose Manhattan distance is at most K from N given points
Given two arrays A[] and B[] consisting of X and Y coordinates of N distinct points in a plane, and a positive integer K, the task is to check if there exists any point P in the plane such that the Manhattan distance between the point and all the given points is at most K. If there exists any such point P, then print "Yes". Otherwise, print "No". E
7 min read
Pairs with same Manhattan and Euclidean distance
In a given Cartesian plane, there are N points. The task is to find the Number of Pairs of points(A, B) such that Point A and Point B do not coincide.Manhattan Distance and the Euclidean Distance between the points should be equal. Note: Pair of 2 points(A, B) is considered same as Pair of 2 points(B, A). Manhattan Distance = |x2-x1|+|y2-y1|Euclide
11 min read
Maximum the value of a given expression for any pair of coordinates on a 2D plane
Given a sorted 2D array arr[][2] of size N such that (arr[i][0], arr[i][1]) represents the coordinates of ith point in the cartesian plane and an integer K, the task is to find the maximum value of the expression (|arr[i][0] - arr[j][0]| + arr[i][1] + arr[j][1]) such that |arr[i][0] - arr[j][0]| ? K for any possible pair of coordinates (i, j). Exam
7 min read
Sum of Manhattan distances between repetitions in a String
Given a string S of size N consisting of lowercase characters, the task is to find the sum of Manhattan distance between each pair (i, j) such that i?j and S[j] = S[i]. Examples: Input: S = "ababa"Output: 10Explanation: The pairs having same characters are: (1, 3), (1, 5), (2, 4) and (3, 5). Therefore, the sum of Manhattan distance will be |3 – 1|
8 min read
three90RightbarBannerImg