Subarreglo de longitud máxima con diferencia entre elementos adyacentes como 0 o 1

Dada una array de n enteros. La tarea es encontrar la longitud máxima del subarreglo tal que la diferencia absoluta entre todos los elementos consecutivos del subarreglo sea 0 o 1 .
Ejemplos: 
 

Entrada: arr[] = {2, 5, 6, 3, 7, 6, 5, 8} 
Salida:
{5, 6} y {7, 6, 5} son los únicos subconjuntos válidos.
Entrada: arr[] = {-2, -1, 5, -1, 4, 0, 3} 
Salida:
 

Enfoque: a partir del primer elemento de la array, busque la primera sub-array válida y almacene su longitud y luego, a partir del siguiente elemento (el primer elemento que no se incluyó en la primera sub-array), busque otra sub-array válida. formación. Repita el proceso hasta que se hayan encontrado todos los subconjuntos válidos y luego imprima la longitud del subconjunto máximo.
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 length
// of the sub-array such that the
// absolute difference between every two
// consecutive elements is either 1 or 0
int getMaxLength(int arr[],int n)
{
    int l = n;
    int i = 0, maxlen = 0;
    while (i < l)
    {
        int j = i;
        while (i+1 < l &&
             (abs(arr[i] - arr[i + 1]) == 1 ||
             abs(arr[i] - arr[i + 1]) == 0))
        {
            i++;
        }
 
            // Length of the valid sub-array currently
            // under consideration
            int currLen = i - j + 1;
 
            // Update the maximum length
            if (maxlen < currLen)
                maxlen = currLen;
 
            if (j == i)
                i++;
    }
 
    // Any valid sub-array cannot be of length 1
    //maxlen = (maxlen == 1) ? 0 : maxlen;
 
    // Return the maximum possible length
    return maxlen;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << getMaxLength(arr, n);
}
 
// This code is contributed by
// Surendra_Gangwar

Java

// Java implementation of the approach
public class GFG {
 
    // Function to return the maximum length
    // of the sub-array such that the
    // absolute difference between every two
    // consecutive elements is either 1 or 0
    public static int getMaxLength(int arr[])
    {
 
        int l = arr.length;
        int i = 0, maxlen = 0;
        while (i < l) {
            int j = i;
            while (i + 1 < l
                   && (Math.abs(arr[i] - arr[i + 1]) == 1
                       || Math.abs(arr[i] - arr[i + 1]) == 0)) {
                i++;
            }
 
            // Length of the valid sub-array currently
            // under cosideration
            int currLen = i - j + 1;
 
            // Update the maximum length
            if (maxlen < currLen)
                maxlen = currLen;
 
            if (j == i)
                i++;
        }
 
        // Any valid sub-array cannot be of length 1
        maxlen = (maxlen == 1) ? 0 : maxlen;
 
        // Return the maximum possible length
        return maxlen;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 2, 4 };
        System.out.print(getMaxLength(arr));
    }
}

Python3

# Python3 implementation of the approach
 
# Function to return the maximum length
# of the sub-array such that the
# absolute difference between every two
# consecutive elements is either 1 or 0
def getMaxLength(arr, n) :
     
    l = n;
    i = 0; maxlen = 0;
     
    while (i < l) :
        j = i;
        while (i + 1 < l and
              (abs(arr[i] - arr[i + 1]) == 1 or
               abs(arr[i] - arr[i + 1]) == 0)) :
         
            i += 1;
         
        # Length of the valid sub-array
        # currently under cosideration
        currLen = i - j + 1;
 
        # Update the maximum length
        if (maxlen < currLen) :
            maxlen = currLen;
 
        if (j == i) :
            i += 1;
     
    # Any valid sub-array cannot be of length 1
    # maxlen = (maxlen == 1) ? 0 : maxlen;
 
    # Return the maximum possible length
    return maxlen;
     
# Driver code
if __name__ == "__main__" :
 
    arr = [ 2, 4 ];
    n = len(arr)
    print(getMaxLength(arr, n));
 
# This code is contributed by Ryuga

C#

// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function to return the maximum length
    // of the sub-array such that the
    // Absolute difference between every two
    // consecutive elements is either 1 or 0
    public static int getMaxLength(int []arr)
    {
 
        int l = arr.Length;
        int i = 0, maxlen = 0;
        while (i < l)
        {
            int j = i;
            while (i + 1 < l &&
                    (Math.Abs(arr[i] - arr[i + 1]) == 1 ||
                    Math.Abs(arr[i] - arr[i + 1]) == 0))
            {
                i++;
            }
 
            // Length of the valid sub-array currently
            // under consideration
            int currLen = i - j + 1;
 
            // Update the maximum length
            if (maxlen < currLen)
                maxlen = currLen;
 
            if (j == i)
                i++;
        }
 
        // Any valid sub-array cannot be of length 1
        maxlen = (maxlen == 1) ? 0 : maxlen;
 
        // Return the maximum possible length
        return maxlen;
    }
 
    // Driver code
    public static void Main(String []args)
    {
        int []arr = { 2, 4 };
        Console.Write(getMaxLength(arr));
    }
}
 
// This code is contributed by Arnab Kundu

PHP

<?php
// PHP implementation of the approach
 
// Function to return the maximum length
// of the sub-array such that the
// absolute difference between every two
// consecutive elements is either 1 or 0
function getMaxLength($arr, $n)
{
    $l = $n;
    $i = 0;
    $maxlen = 0;
    while ($i < $l)
    {
        $j = $i;
        while ($i + 1 < $l &&
              (abs($arr[$i] - $arr[$i + 1]) == 1 ||
                abs($arr[$i] - $arr[$i + 1]) == 0))
        {
            $i++;
        }
 
        // Length of the valid sub-array
        // currently under consideration
        $currLen = $i - $j + 1;
 
        // Update the maximum length
        if ($maxlen < $currLen)
            $maxlen = $currLen;
 
        if ($j == $i)
            $i++;
    }
 
    // Any valid sub-array cannot be of length 1
    //maxlen = (maxlen == 1) ? 0 : maxlen;
 
    // Return the maximum possible length
    return $maxlen;
}
 
// Driver code
$arr = array(2, 4 );
$n = sizeof($arr);
echo getMaxLength($arr, $n)
 
// This code is contributed by ita_c
?>

Javascript

<script>
 
// Javascript implementation of the approach
 
// Function to return the maximum length
    // of the sub-array such that the
    // absolute difference between every two
    // consecutive elements is either 1 or 0
function getMaxLength(arr)
{
    let l = arr.length;
        let i = 0, maxlen = 0;
        while (i < l) {
            let j = i;
            while (i + 1 < l
                   && (Math.abs(arr[i] - arr[i + 1]) == 1
                       || Math.abs(arr[i] - arr[i + 1]) == 0)) {
                i++;
            }
   
            // Length of the valid sub-array currently
            // under cosideration
            let currLen = i - j + 1;
   
            // Update the maximum length
            if (maxlen < currLen)
                maxlen = currLen;
   
            if (j == i)
                i++;
        }
   
        // Any valid sub-array cannot be of length 1
        //maxlen = (maxlen == 1) ? 0 : maxlen;
   
        // Return the maximum possible length
        return maxlen;
}
 
// Driver code
let arr = [2, 4 ];
document.write(getMaxLength(arr));
 
// This code is contributed by rag2127.
</script>
Producción: 

1

 

Complejidad de tiempo: O (n), donde n es el tamaño de la array dada.

Complejidad espacial: O (1), ya que no estamos utilizando ningún espacio adicional.

Publicación traducida automáticamente

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