Dada una array arr[] que consta de N coordenadas enteras, la tarea es encontrar la distancia máxima de Manhattan entre dos pares distintos de coordenadas.
La Distancia Manhattan entre dos puntos (X1, Y1) y (X2, Y2) viene dada por |X1 – X2| + |Y1 – Y2| .
Ejemplos:
Entrada: arr[] = {(1, 2), (2, 3), (3, 4)}
Salida: 4
Explicación:
La distancia máxima de Manhattan se encuentra entre (1, 2) y (3, 4), es decir, |3 – 1| + |4- 2 | = 4.Entrada: arr[] = {(-1, 2), (-4, 6), (3, -4), (-2, -4)}
Salida: 17
Explicación:
La distancia máxima de Manhattan se encuentra entre (- 4, 6) y (3, -4) es decir, |-4 – 3| + |6 – (-4)| = 17.
Enfoque ingenuo: el enfoque más simple es iterar sobre la array y, para cada coordenada, calcular su distancia Manhattan desde todos los puntos restantes. Sigue actualizando la distancia máxima obtenida después de cada cálculo. Finalmente, imprima la distancia máxima obtenida.
A continuación se muestra la implementación del enfoque anterior:
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>
4
Complejidad de tiempo: O(N 2 ), donde N es el tamaño de la array dada.
Espacio Auxiliar: O(1)
Enfoque eficiente: la idea es usar sumas y diferencias almacenadas entre las coordenadas X e Y y encontrar la respuesta clasificando esas diferencias. A continuación se presentan las observaciones al enunciado del problema anterior:
- Manhattan La distancia entre dos puntos cualesquiera (X i , Y i ) y (X j , Y j ) se puede escribir de la siguiente manera:
| Xi – Xj | + | Yi – Yj | = máx(X i – X j -Y i + Y j ,
-X i + X j + Y i – Y j ,
-X i + X j – Y i + Y j ,
X i – Xj + Y i – Y j ).
- La expresión anterior se puede reorganizar como:
| Xi – Xj | + | Yi – Yj | = máx((X i – Y i ) – (X j – Y j ),
(-X i + Y i ) – (-X j + Y j ),
(-X i – Y i ) – (-X j – Yj ),
( Xi + Yi ) – ( Xj + Yj ))
- Se puede observar a partir de la expresión anterior, que la respuesta se puede encontrar almacenando la suma y la diferencia de las coordenadas.
Siga los pasos a continuación para resolver el problema:
- Inicialice dos arrays sum[] y diff[] .
- Almacene la suma de las coordenadas X e Y , es decir, X i + Y i en sum[] y su diferencia, es decir, X i – Y i en diff[] .
- Ordene sum[] y diff[] en orden ascendente.
- El máximo de los valores ( sum[N-1] – sum[0]) y (diff[N-1] – diff[0]) es el resultado requerido.
A continuación se muestra la implementación del enfoque anterior:
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>
4
Complejidad de tiempo: O(N*log N)
Espacio auxiliar: O(N)
Mejora del enfoque eficiente : en lugar de almacenar las sumas y las diferencias en una array auxiliar y luego ordenar las arrays para determinar el mínimo y el máximo, es posible mantener un total acumulado de las sumas y diferencias extremas.
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
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>
4
Complejidad de Tiempo : O(N)
Espacio Auxiliar : O(1)
Las ideas presentadas aquí son en dos dimensiones, pero pueden extenderse a otras dimensiones. Cada dimensión adicional requiere el doble de la cantidad de cálculos en cada punto. Por ejemplo, en el espacio tridimensional, el resultado es la diferencia máxima entre los cuatro pares de extremos calculados a partir de x+y+z, x+yz, x-y+z y xyz.
Publicación traducida automáticamente
Artículo escrito por koulick_sadhu y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA