Encuentre el máximo en una array sin usar operadores relacionales

Dada una array A[] de enteros no negativos, encuentre el máximo en la array sin usar el Operador relacional .

Ejemplos: 

Input : A[] = {2, 3, 1, 4, 5}
Output : 5

Input : A[] = {23, 17, 93}
Output : 93

Usamos restas repetidas para encontrar el máximo. Para encontrar el máximo entre dos números, tomamos un contador variable inicializado a cero. Seguimos disminuyendo ambos valores hasta que ambos se vuelven iguales a cero (Nota: el primer valor en convertirse en cero no se reduce más), aumentando el contador simultáneamente. Si bien ambos valores se vuelven cero, el contador ha aumentado para ser el máximo de ambos. Primero encontramos el máximo de los primeros dos números y luego lo comparamos con el resto de elementos de la array uno por uno para encontrar el máximo general.

A continuación se muestra la implementación de la idea anterior.

C++

#include <iostream>
using namespace std;
 
// Function to find maximum between two non-negative
// numbers without using relational operator.
int maximum(int x, int y)
{
    int c = 0;
 
    // Continues till both becomes zero.
    while(x || y)
    {
        // decrement if the value is not already zero
        if(x)
        x--;
 
        if(y)
        y--;
        c++;
    }
    return c;
}
 
// Function to find maximum in an array.
int arrayMaximum(int A[], int N)
{
    // calculating maximum of first two numbers
    int mx = A[0];
     
    // Iterating through each of the member of the array
    // to calculate the maximum
    for (int i = N-1; i; i--)
 
        // Finding the maximum between current maximum
       // and current value.
        mx = maximum(mx, A[i]);
     
    return mx;
}
 
// Driver code
int main()
{
    // Array declaration
    int A[] = {4, 8, 9, 18};
    int N = sizeof(A) / sizeof(A[0]);
     
    // Calling Function to find the maximum of the Array
    cout << arrayMaximum(A, N);
    return 0;
}

Java

import java.io.*;
 
class GFG {
     
    // Function to find maximum between two
    // non-negative numbers without using
    // relational operator.
    static int maximum(int x, int y)
    {
        int c = 0;
 
        // Continues till both becomes zero.
        while (x > 0 || y > 0) {
             
            // decrement if the value is not
            // already zero
            if (x > 0)
                x--;
 
            if (y > 0)
                y--;
            c++;
        }
         
        return c;
    }
 
    // Function to find maximum in an array.
    static int arrayMaximum(int A[], int N)
    {
         
        // calculating maximum of first
        // two numbers
        int mx = A[0];
 
        // Iterating through each of the
        // member of the array to calculate
        // the maximum
        for (int i = N - 1; i > 0; i--)
 
            // Finding the maximum between
            // current maximum and current
            // value.
            mx = maximum(mx, A[i]);
 
        return mx;
    }
 
    // Driver code
    public static void main(String[] args)
    {
         
        // Array declaration
        int A[] = { 4, 8, 9, 18 };
        int N = A.length;
 
        // Calling Function to find the maximum
        // of the Array
        System.out.print(arrayMaximum(A, N));
    }
}
 
// This code is contributed by vt_m.

Python3

# Function to find maximum between two
# non-negative numbers without using
# relational operator.
def maximum(x, y):
    c = 0
 
    # Continues till both becomes zero.
    while(x or y):
         
        # decrement if the value is
        # not already zero
        if(x):
            x -= 1
 
        if(y):
            y -= 1
        c += 1
 
    return c
 
# Function to find maximum in an array.
def arrayMaximum(A, N):
     
    # calculating maximum of
    # first two numbers
    mx = A[0]
     
    # Iterating through each of
    # the member of the array
    # to calculate the maximum
    i = N - 1
    while(i):
         
        # Finding the maximum between
        # current maximum and current value.
        mx = maximum(mx, A[i])
        i -= 1
     
    return mx
 
# Driver code
if __name__ == '__main__':
     
    # Array declaration
    A = [4, 8, 9, 18]
    N = len(A)
     
    # Calling Function to find the
    # maximum of the Array
    print(arrayMaximum(A, N))
     
# This code is contributed by
# Surendra_Gangwar

C#

// C# program to Find maximum
// in an array without using
// Relational Operators
using System;
 
class GFG
{
     
    // Function to find maximum
    // between two non-negative
    // numbers without using
    // relational operator.
    static int maximum(int x,
                       int y)
    {
        int c = 0;
 
        // Continues till
        // both becomes zero.
        while (x > 0 || y > 0)
        {
             
            // decrement if
            // the value is not
            // already zero
            if (x > 0)
                x--;
 
            if (y > 0)
                y--;
            c++;
        }
         
        return c;
    }
 
    // Function to find
    // maximum in an array.
    static int arrayMaximum(int []A,
                            int N)
    {
         
        // calculating
        // maximum of first
        // two numbers
        int mx = A[0];
 
        // Iterating through
        // each of the member
        // of the array to
        // calculate the maximum
        for (int i = N - 1;
                 i > 0; i--)
 
            // Finding the maximum
            // between current
            // maximum and current
            // value.
            mx = maximum(mx, A[i]);
 
        return mx;
    }
 
    // Driver code
    public static void Main()
    {
         
        // Array declaration
        int []A = { 4, 8, 9, 18 };
        int N = A.Length;
 
        // Calling Function to
        // find the maximum
        // of the Array
        Console.WriteLine(arrayMaximum(A, N));
    }
}
 
// This code is contributed
// by anuj_67.

PHP

<?php
// Function to find maximum
// between two non-negative
// numbers without using
// relational operator.
function maximum($x, $y)
{
    $c = 0;
 
    // Continues till
    // both becomes zero.
    while($x or $y)
    {
        // decrement if the value
        // is not already zero
        if($x)
        $x--;
 
        if($y)
        $y--;
        $c++;
    }
    return $c;
}
 
// Function to find
// maximum in an array.
function arrayMaximum($A, $N)
{
    // calculating maximum of
    // first two numbers
    $mx = $A[0];
     
    // Iterating through each of
    // the member of the array
    // to calculate the maximum
    for ( $i = $N - 1; $i; $i--)
 
        // Finding the maximum
        // between current maximum
        // and current value.
        $mx = maximum($mx, $A[$i]);
     
    return $mx;
}
 
// Driver code
 
// Array declaration
$A = array(4, 8, 9, 18);
$N = count($A);
 
// Calling Function to find
// the maximum of the Array
echo arrayMaximum($A, $N);
 
// This code is contributed
// by anuj_67.
?>

Javascript

<script>
    // Javascript program to Find maximum
    // in an array without using
    // Relational Operators
     
    // Function to find maximum
    // between two non-negative
    // numbers without using
    // relational operator.
    function maximum(x, y)
    {
        let c = 0;
   
        // Continues till
        // both becomes zero.
        while (x > 0 || y > 0)
        {
               
            // decrement if
            // the value is not
            // already zero
            if (x > 0)
                x--;
   
            if (y > 0)
                y--;
            c++;
        }
           
        return c;
    }
   
    // Function to find
    // maximum in an array.
    function arrayMaximum(A, N)
    {
           
        // calculating
        // maximum of first
        // two numbers
        let mx = A[0];
   
        // Iterating through
        // each of the member
        // of the array to
        // calculate the maximum
        for (let i = N - 1; i > 0; i--)
   
            // Finding the maximum
            // between current
            // maximum and current
            // value.
            mx = maximum(mx, A[i]);
   
        return mx;
    }
     
    // Array declaration
    let A = [ 4, 8, 9, 18 ];
    let N = A.length;
 
    // Calling Function to
    // find the maximum
    // of the Array
    document.write(arrayMaximum(A, N));
     
    // This code is contributed by divyesh072019.
</script>

Producción: 

18

La complejidad temporal del código será O(N*max) donde max es el máximo de los elementos de la array.

Limitaciones : esto solo funcionará si la array contiene todos los enteros no negativos.

Publicación traducida automáticamente

Artículo escrito por ShivamKD 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 *