Distancia máxima entre dos elementos desiguales

Dada una array arr[] , la tarea es encontrar la distancia máxima entre dos elementos desiguales de la array dada.
Ejemplos: 
 

Entrada: arr[] = {3, 2, 1, 2, 1} 
Salida:
La distancia máxima es entre el primer y el último elemento.
Entrada: arr[] = {3, 3, 1, 3, 3} 
Salida:
 

Enfoque ingenuo: recorra toda la array para cada elemento y encuentre la distancia más larga del elemento que es desigual.
Enfoque eficiente: al utilizar el hecho de que el par de elementos desiguales debe incluir el primer o el último elemento o ambos, calcule la distancia más larga entre los elementos desiguales atravesando la array ya sea fijando el primer elemento o fijando el último elemento.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the maximum distance
// between two unequal elements
int maxDistance(int arr[], int n)
{
    // If first and last elements are unequal
    // they are maximum distance apart
    if (arr[0] != arr[n - 1])
        return (n - 1);
 
    int i = n - 1;
 
    // Fix first element as one of the elements
    // and start traversing from the right
    while (i > 0) {
 
        // Break for the first unequal element
        if (arr[i] != arr[0])
            break;
        i--;
    }
 
    // To store the distance from the first element
    int distFirst = (i == 0) ? -1 : i;
 
    i = 0;
 
    // Fix last element as one of the elements
    // and start traversing from the left
    while (i < n - 1) {
 
        // Break for the first unequal element
        if (arr[i] != arr[n - 1])
            break;
        i++;
    }
 
    // To store the distance from the last element
    int distLast = (i == n - 1) ? -1 : (n - 1 - i);
 
    // Maximum possible distance
    int maxDist = max(distFirst, distLast);
    return maxDist;
}
 
// Driver code
int main()
{
    int arr[] = { 4, 4, 1, 2, 1, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << maxDistance(arr, n);
 
    return 0;
}

Java

// Java implementation of the approach
import java.io.*;
 
class GFG
{
 
// Function to return the maximum distance
// between two unequal elements
static int maxDistance(int arr[], int n)
{
    // If first and last elements are unequal
    // they are maximum distance apart
    if (arr[0] != arr[n - 1])
        return (n - 1);
 
    int i = n - 1;
 
    // Fix first element as one of the elements
    // and start traversing from the right
    while (i > 0)
    {
 
        // Break for the first unequal element
        if (arr[i] != arr[0])
            break;
        i--;
    }
 
    // To store the distance from the first element
    int distFirst = (i == 0) ? -1 : i;
 
    i = 0;
 
    // Fix last element as one of the elements
    // and start traversing from the left
    while (i < n - 1)
    {
 
        // Break for the first unequal element
        if (arr[i] != arr[n - 1])
            break;
        i++;
    }
 
    // To store the distance from the last element
    int distLast = (i == n - 1) ? -1 : (n - 1 - i);
 
    // Maximum possible distance
    int maxDist = Math.max(distFirst, distLast);
    return maxDist;
}
 
// Driver code
public static void main (String[] args)
{
    int arr[] = { 4, 4, 1, 2, 1, 4 };
    int n = arr.length;
    System.out.print(maxDistance(arr, n));
}
}
 
// This code is contributed by anuj_67..

Python3

# Python implementation of the approach
 
# Function to return the maximum distance
# between two unequal elements
def maxDistance(arr, n):
     
    # If first and last elements are unequal
    # they are maximum distance apart
    if (arr[0] != arr[n - 1]):
        return (n - 1);
 
    i = n - 1;
 
    # Fix first element as one of the elements
    # and start traversing from the right
    while (i > 0):
 
        # Break for the first unequal element
        if (arr[i] != arr[0]):
            break;
        i-=1;
 
    # To store the distance from the first element
    distFirst = -1 if(i == 0) else i;
 
    i = 0;
 
    # Fix last element as one of the elements
    # and start traversing from the left
    while (i < n - 1):
 
        # Break for the first unequal element
        if (arr[i] != arr[n - 1]):
            break;
        i+=1;
 
    # To store the distance from the last element
    distLast = -1 if(i == n - 1) else (n - 1 - i);
 
    # Maximum possible distance
    maxDist = max(distFirst, distLast);
    return maxDist;
 
# Driver code
arr = [4, 4, 1, 2, 1, 4];
n = len(arr);
print(maxDistance(arr, n));
 
# This code has been contributed by 29AjayKumar

C#

// C# implementation of the approach
using System;
 
class GFG
{
     
// Function to return the maximum distance
// between two unequal elements
static int maxDistance(int []arr, int n)
{
    // If first and last elements are unequal
    // they are maximum distance apart
    if (arr[0] != arr[n - 1])
        return (n - 1);
 
    int i = n - 1;
 
    // Fix first element as one of the elements
    // and start traversing from the right
    while (i > 0)
    {
 
        // Break for the first unequal element
        if (arr[i] != arr[0])
            break;
        i--;
    }
 
    // To store the distance from the first element
    int distFirst = (i == 0) ? -1 : i;
 
    i = 0;
 
    // Fix last element as one of the elements
    // and start traversing from the left
    while (i < n - 1)
    {
 
        // Break for the first unequal element
        if (arr[i] != arr[n - 1])
            break;
        i++;
    }
 
    // To store the distance from the last element
    int distLast = (i == n - 1) ? -1 : (n - 1 - i);
 
    // Maximum possible distance
    int maxDist = Math.Max(distFirst, distLast);
    return maxDist;
}
 
// Driver code
static public void Main ()
{
    int []arr = { 4, 4, 1, 2, 1, 4 };
    int n = arr.Length;
    Console.WriteLine(maxDistance(arr, n));
}
}
 
// This code is contributed by Tushil..

Javascript

<script>
 
// Javascript implementation of the approach
 
// Function to return the maximum distance
// between two unequal elements
function maxDistance(arr, n)
{
    // If first and last elements are unequal
    // they are maximum distance apart
    if (arr[0] != arr[n - 1])
        return (n - 1);
 
    var i = n - 1;
 
    // Fix first element as one of the elements
    // and start traversing from the right
    while (i > 0) {
 
        // Break for the first unequal element
        if (arr[i] != arr[0])
            break;
        i--;
    }
 
    // To store the distance from the first element
    var distFirst = (i == 0) ? -1 : i;
 
    i = 0;
 
    // Fix last element as one of the elements
    // and start traversing from the left
    while (i < n - 1) {
 
        // Break for the first unequal element
        if (arr[i] != arr[n - 1])
            break;
        i++;
    }
 
    // To store the distance from the last element
    var distLast = (i == n - 1) ? -1 : (n - 1 - i);
 
    // Maximum possible distance
    var maxDist = Math.max(distFirst, distLast);
    return maxDist;
}
 
// Driver code
var arr = [ 4, 4, 1, 2, 1, 4 ];
var n = arr.length;
document.write( maxDistance(arr, n));
 
</script>
Producción: 

4

 

Complejidad temporal: O(n)
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por Shivam.Pradhan y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *