Longitud del subarreglo más largo que consiste solo en 1s

Dada una array arr[] de tamaño N , que consiste en valores binarios, la tarea es encontrar el subarreglo no vacío más largo que consta solo de 1 s después de la eliminación de un solo elemento de la array.

Ejemplos:

Entrada: arr[] = {1, 1, 1}
Salida: 2

Entrada: arr[] = {0, 0, 0}
Salida: 0

Enfoque: siga los pasos a continuación para resolver el problema:

  • Inicialice tres variables, newLen = 0 , prevLen = 0 , maxLen = 0 .
  • Recorra la array arr[] agregando cero al principio:
    • Si arr[i] = 1: Incremente newLen y prevLen en 1 .
    • De lo contrario:
      • Asigne el valor máximo a la variable maxLen .
      • Establezca prevLen = newLen y newLen = 0 .
  • Imprime maxLen si maxLen < len(arr) .
  • De lo contrario, imprima maxLen – 1 .

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;
 
// Utility function to find the length of
// longest subarray containing only 1s
int longestSubarrayUtil(vector<int> arr, int n)
{
    int neww = 0, old = 0, m = 0;
     
    // Traverse the array
    for(int x = 0; x <= n; x++)
    {
         
        // If array element is 1
        if (arr[x] == 1)
        {
             
            // Increment both by 1
            neww += 1;
            old += 1;
        }
        else
        {
             
            // Assign maximum value
            m = max(m, old);
 
            //Assign new to old
            // and set new to zero
            old = neww;
            neww = 0;
        }
    }
    
    // Return the final length
    if (m < n)
    {
        return m;
    }
    else return m - 1;
}
 
// Function to find length of the
// longest subarray containing only 1's
void longestSubarray(vector<int> arr, int n)
{
     
    // Stores the length of longest
    // subarray consisting of 1s
    int len = longestSubarrayUtil(arr, n);
 
    // Print the length
    // of the subarray
    cout << len;
}
 
// Driver code
int main()
{
     
    // Given array
    vector<int> arr = {1, 1, 1};
    int n = arr.size();
     
    // Append 0 at beginning
    for(int i = n; i >= 0; i--)
    {
        arr[i] = arr[i - 1];
    }
    arr[0] = 0;
     
    // Function call to find the longest
    // subarray containing only 1's
    longestSubarray(arr, n);
}
 
// This code is contributed by SoumikMondal

Java

// Java program for the above approach
import java.util.*;
 
class GFG
{
 
// Utility function to find the length of
// longest subarray containing only 1s
static int longestSubarrayUtil(int [] arr, int n)
{
    int neww = 0, old = 0, m = 0;
     
    // Traverse the array
    for(int x = 0; x <n; x++)
    {
         
        // If array element is 1
        if (arr[x] == 1)
        {
             
            // Increment both by 1
            neww += 1;
            old += 1;
        }
        else
        {
             
            // Assign maximum value
            m = Math.max(m, old);
 
            //Assign new to old
            // and set new to zero
            old = neww;
            neww = 0;
        }
    }
    m = Math.max(m, old);
    // Return the final length
    if(m<n)
        return m;
    else
        return m-1;
}
 
// Function to find length of the
// longest subarray containing only 1's
static void longestSubarray(int []arr, int n)
{
     
    // Stores the length of longest
    // subarray consisting of 1s
    int len = longestSubarrayUtil(arr, n);
 
    // Print the length
    // of the subarray
    System.out.print(len);
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given array
    int arr[] = {1, 1, 1};
    int n = arr.length;
   
    // Function call to find the longest
    // subarray containing only 1's
    longestSubarray(arr, n);
}
}
 
// This code is contributed by amreshkumar3.

C#

using System;
 
public class GFG {
 
  // Function to find length of the
  // longest subarray containing only 1's
  static void longestSubarray(int[] arr, int n)
  {
 
    // Stores the length of longest
    // subarray consisting of 1s
    int len = longestSubarrayUtil(arr, n);
 
    // Print the length
    // of the subarray
    Console.WriteLine(len);
  }
 
  // Utility function to find the length of
  // longest subarray containing only 1s
  static int longestSubarrayUtil(int[] arr, int n)
  {
    int neww = 0, old = 0, m = 0;
 
    // Traverse the array
    for (int x = 0; x < n; x++) {
 
      // If array element is 1
      if (arr[x] == 1) {
 
        // Increment both by 1
        neww += 1;
        old += 1;
      }
      else {
 
        // Assign maximum value
        m = Math.Max(m, old);
 
        // Assign new to old
        // and set new to zero
        old = neww;
        neww = 0;
      }
    }
    m = Math.Max(m, old);
    // Return the final length
    if (m < n)
      return m;
    else
      return m - 1;
  }
 
  static public void Main()
  {
 
    // Code
    // Given array
    int[] arr = { 1, 1, 1 };
    int n = arr.Length;
 
    // Function call to find the longest
    // subarray containing only 1's
    longestSubarray(arr, n);
  }
}
 
// this code is contributed by devendra solunke

Python3

# Python3 program for the above approach
 
# Utility function to find the length of
# longest subarray containing only 1s
def longestSubarrayUtil(arr):
 
    new, old, m = 0, 0, 0
 
    # Traverse the array
    for x in arr+[0]:
 
        # If array element is 1
        if x == 1:
 
            # Increment both by 1
            new += 1
            old += 1
        else:
 
            # Assign maximum value
            m = max(m, old)
 
            # Assign new to old
            # and set new to zero
            old, new = new, 0
 
    # Return the final length
    return m if m < len(arr) else m - 1
 
# Function to find length of the
# longest subarray containing only 1's
def longestSubarray(arr):
 
    # Stores the length of longest
    # subarray consisting of 1s
    len = longestSubarrayUtil(arr)
 
    # Print the length
    # of the subarray
    print(len)
 
 
# Given array
arr = [1, 1, 1]
 
# Function call to find the longest
# subarray containing only 1's
longestSubarray(arr)

Javascript

<script>
 
// JavaScript program for the above approach
 
// Utility function to find the length of
// longest subarray containing only 1s
function longestSubarrayUtil(arr, n)
{
    var neww = 0, old = 0, m = 0;
     
    // Traverse the array
    for(var x = 0; x <= n; x++)
    {
         
        // If array element is 1
        if (arr[x] == 1)
        {
             
            // Increment both by 1
            neww += 1;
            old += 1;
        }
        else
        {
             
            // Assign maximum value
            m = Math.max(m, old);
 
            //Assign new to old
            // and set new to zero
            old = neww;
            neww = 0;
        }
    }
    
    // Return the final length
    if (m < n)
    {
        return m;
    }
    else
    {
        return m - 1;
    }
}
 
// Function to find length of the
// longest subarray containing only 1's
function longestSubarray(arr, n)
{
     
    // Stores the length of longest
    // subarray consisting of 1s
    var len = longestSubarrayUtil(arr, n);
 
    // Print the length
    // of the subarray
    document.write( len);
}
 
// Driver code
// Given array
var arr = [1, 1, 1];
var n = arr.length;
 
// Append 0 at beginning
for(var i = n-1; i >= 0; i--)
{
    arr[i] = arr[i - 1];
}
arr[0] = 0;
 
// Function call to find the longest
// subarray containing only 1's
longestSubarray(arr, n);
 
 
</script>
Producción: 

2

 

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

Publicación traducida automáticamente

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