Longitud del subarreglo más largo con solo elementos pares

Dada una array arr[]. La tarea es encontrar la longitud del subarreglo más largo de arr[] tal que contenga solo elementos pares.
Ejemplos: 
 

Input : arr[] = { 5, 2, 4, 7 }
Output : Length = 2
subArr[] = {2, 4}

Input : arr[] = {9, 8, 5, 4, 4, 4, 2, 4, 1}
Output : Length 5
subArr[] = {4, 4, 4, 2, 4}

La idea es observar que el subarreglo más grande con solo elementos pares es el número máximo de elementos pares contiguos en el arreglo. Por lo tanto, la tarea ahora se reduce a encontrar el número máximo de elementos pares contiguos en la array.
Para hacer esto, recorra la array usando dos variables, ans y current_count . La variable ans almacena la respuesta final y current_count almacena la longitud del subarreglo con solo números pares.
Ahora, cada vez que se encuentre un elemento par, siga incrementando el conteo_actual y cada vez que se encuentre un elemento IMPAR, tome el máximo de ans y el conteo_actual y restablezca el conteo_actual a cero.
Al final, ans almacenará la longitud del subarreglo más grande con solo elementos pares.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

   
// C++ Program to find the Length of the
// largest Subarray with only even elements
 
#include <cmath>
#include <iostream>
using namespace std;
 
// Function to find the Length of the
// largest Subarray with only even elements
int maxEvenSubarray(int array[], int N)
{
    int ans = 0;
    int count = 0;
 
    // Iterate the loop
    for (int i = 0; i < N; i++) {
 
        // Check whether the element is
        // even in continuous fashion
        if (array[i] % 2 == 0) {
            count++;
            ans = max(ans, count);
        }
 
        else {
             
            // If element are not even in continuous
            // fashion, Reinitialize the count
            count = 0;
        }
    }
 
    // Check for the last element in the array
    ans = max(ans, count);
    return ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 9, 8, 5, 4, 4, 4, 2, 4, 1 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << maxEvenSubarray(arr, N);
 
    return 0;
}

Java

// Java Program to find the Length of the longest
// Subarray with only Even Elements
public class GFG {
 
    // Function to find the Length of the longest
    // Subarray with only Even Elements
    static int maxEvenSubarray(int array[], int N)
    {
        int ans = 0;
        int count = 0;
 
        // Iterate the loop
        for (int i = 0; i < array.length; i++) {
 
            // Check whether the element is
            // even in continuous fashion
            if (array[i] % 2 == 0) {
                count++;
                ans = Math.max(ans, count);
            }
 
            else {
                // If element are not even in continuous
                // fashion. Reinitialize the count
                count = 0;
            }
        }
 
        // Check for the last element in the array
        ans = Math.max(ans, count);
        return ans;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int arr[] = { 9, 8, 5, 4, 4, 4, 2, 4, 1 };
 
        int N = arr.length;
 
        System.out.println(maxEvenSubarray(arr, N));
    }
}

Python3

# Python3 Program to find the Length of the
# largest Subarray with only even elements
 
# Function to find the Length of the
# largest Subarray with only even elements
def maxEvenSubarray(array,N):
    ans = 0
    count = 0
 
    # Iterate the loop
    for i in range(0,N):
         
        # Check whether the element is
        # even in continuous fashion
        if array[i]%2==0:
            count +=1
            ans = max(ans,count)
 
        else:
 
            # If element are not even in continuous
            # fashion, Reinitialize the count
            count = 0
             
    # Check for the last element in the array
    ans = max(ans,count)
    return ans
 
# Driver code
if __name__=='__main__':
    arr = [9, 8, 5, 4, 4, 4, 2, 4, 1]
    N = len(arr)
    print(maxEvenSubarray(arr,N))
 
# This article is contributed by Shrikant13

C#

// C# Program to find the Length
// of the largest Subarray with
// only even elements
using System;
 
class GFG
{
// Function to find the Length
// of the largest Subarray with
// only even elements
static int maxEvenSubarray(int []array,
                           int N)
{
    int ans = 0;
    int count = 0;
 
    // Iterate the loop
    for (int i = 0; i < N; i++)
    {
        // Check whether the element is
        // even in continuous fashion
        if (array[i] % 2 == 0)
        {
            count++;
            ans = Math.Max(ans, count);
        }
        else
        {
            // If element are not even in
            // continuous fashion,
            // Reinitialize the count
            count = 0;
        }
    }
 
    // Check for the last
    // element in the array
    ans = Math.Max(ans, count);
    return ans;
}
 
// Driver Code
public static void Main()
{
    int []arr = { 9, 8, 5, 4,
                  4, 4, 2, 4, 1 };
 
    int N = arr.Length;
 
    Console.WriteLine(maxEvenSubarray(arr, N));
}
}
 
// This code is contributed by ihritik

PHP

<?php
// PHP Program to find the Length
// of the largest Subarray with
// only even elements
 
// Function to find the Length
// of the largest Subarray with
// only even elements
function maxEvenSubarray($array, $N)
{
    $ans = 0;
    $count = 0;
 
    // Iterate the loop
    for ($i = 0; $i < $N; $i++)
    {
        // Check whether the element is
        // even in continuous fashion
        if ($array[$i] % 2 == 0)
        {
            $count++;
            $ans = max($ans, $count);
        }
        else
        {
            // If element are not even in
            // continuous fashion,
            // Reinitialize the count
            $count = 0;
        }
    }
 
    // Check for the last
    // element in the array
    $ans = max($ans, $count);
    return $ans;
}
 
// Driver Code
$arr = array( 9, 8, 5, 4,
              4, 4, 2, 4, 1 );
$N = sizeof($arr);
 
echo maxEvenSubarray($arr, $N);
 
// This code is contributed by ihritik
?>

Javascript

<script>
// Javascript Program to find the Length
// of the largest Subarray with
// only even elements
 
// Function to find the Length
// of the largest Subarray with
// only even elements
function maxEvenSubarray(array, N)
{
    let ans = 0;
    let count = 0;
 
    // Iterate the loop
    for (let i = 0; i < N; i++)
    {
        // Check whether the element is
        // even in continuous fashion
        if (array[i] % 2 == 0)
        {
            count++;
            ans = Math.max(ans, count);
        }
        else
        {
            // If element are not even in
            // continuous fashion,
            // Reinitialize the count
            count = 0;
        }
    }
 
    // Check for the last
    // element in the array
    ans = Math.max(ans, count);
    return ans;
}
 
// Driver Code
let arr = new Array( 9, 8, 5, 4,
            4, 4, 2, 4, 1 );
let N = arr.length;
 
document.write(maxEvenSubarray(arr, N));
 
// This code is contributed by _saurabh_jaiswal.
</script>
Producción: 

5

 

Complejidad del tiempo: 
 

Publicación traducida automáticamente

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