Minimice la cantidad de 0 que se deben eliminar para maximizar la longitud de la substring más larga de 1

Dada una string binaria S de longitud N , la tarea es encontrar el número mínimo de 0 que se requiere eliminar de la string S dada para obtener la substring más larga de 1 .

Ejemplos:

Entrada: S = “010011”
Salida: 2
Explicación:
Eliminar str[2] y str[3] modifica la string S a “0111”. Por lo tanto, el número mínimo de eliminaciones requeridas es de 2.

Entrada: S = “011111”
Salida: 0

Enfoque: La idea es encontrar el índice más a la izquierda y más a la derecha de 1 en la string, luego contar el número de 0 presentes entre ellos. Finalmente, imprime el valor del conteo obtenido. Siga los pasos a continuación para resolver el problema:

  • Recorra la string S para encontrar la primera y la última ocurrencia de 1 en la string y almacene sus índices en variables, digamos left y right , respectivamente.
  • Itere sobre el rango [izquierda, derecha] usando la variable i , y si el valor de str[i] es igual a 0 , incremente el conteo en 1.
  • Después de completar los pasos anteriores, imprima el valor de conteo como resultado.

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;
 
// Function to count the minimum number
// of 0s required to be removed to
// maximize the longest substring of 1s
void minNumZeros(string str)
{
    // Stores leftmost and rightmost
    // indices consisting of 1
    int left = INT_MAX, right = INT_MIN;
 
    // Stores the count of 0s
    // between left and right
    int count = 0;
 
    // Traverse the string str
    for (int i = 0; i < str.length(); i++) {
 
        // If the current character is 1
        if (str[i] == '1') {
 
            // Update leftmost and rightmost
            // index consisting of 1
            left = min(i, left);
            right = max(right, i);
        }
    }
 
    // If string consists only of 0s
    if (left == INT_MAX) {
        cout << "0";
        return;
    }
 
    // Count the number of 0s
    // between left and right
    for (int i = left; i < right; i++) {
 
        if (str[i] == '0') {
            count++;
        }
    }
 
    // Print the result
    cout << count;
}
 
// Driver Code
int main()
{
    string str = "010011";
    minNumZeros(str);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to count the minimum number
// of 0s required to be removed to
// maximize the longest substring of 1s
static void minNumZeros(String str)
{
     
    // Stores leftmost and rightmost
    // indices consisting of 1
    int left = Integer.MAX_VALUE;
    int right = Integer.MIN_VALUE;
 
    // Stores the count of 0s
    // between left and right
    int count = 0;
 
    // Traverse the string str
    for(int i = 0; i < str.length(); i++)
    {
         
        // If the current character is 1
        if (str.charAt(i) == '1')
        {
             
            // Update leftmost and rightmost
            // index consisting of 1
            left = Math.min(i, left);
            right = Math.max(right, i);
        }
    }
 
    // If string consists only of 0s
    if (left == Integer.MAX_VALUE)
    {
        System.out.print("0");
        return;
    }
 
    // Count the number of 0s
    // between left and right
    for(int i = left; i < right; i++)
    {
        if (str.charAt(i) == '0')
        {
            count++;
        }
    }
 
    // Print the result
    System.out.print(count);
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "010011";
     
    minNumZeros(str);
}
}
 
// This code is contributed by Dharanendra L V

Python3

# Python program for the above approach
import sys
 
# Function to count the minimum number
# of 0s required to be removed to
# maximize the longest substring of 1s
def minNumZeros(st) :
 
    # Stores leftmost and rightmost
    # indices consisting of 1
    left = sys.maxsize
    right = -sys.maxsize - 1
 
    # Stores the count of 0s
    # between left and right
    count = 0
 
    # Traverse the string str
    for i in range(len(st)) :
    #for (int i = 0; i < str.length(); i++) {
 
        # If the current character is 1
        if st[i] == '1' :
 
            # Update leftmost and rightmost
            # index consisting of 1
            left = min(i, left)
            right = max(right, i)
         
    # If string consists only of 0s
    if left == sys.maxsize :
        print("0")
        return
     
    # Count the number of 0s
    # between left and right
    for i in range(left,right):
         
    #for (int i = left; i < right; i++) {
 
        if st[i] == '0' :
            count += 1
         
    # Print the result
    print(count)
 
# Driver Code
if __name__ == "__main__" :    
    st = "010011";
    minNumZeros(st)
     
 # This code is contributed by jana_sayantan.  

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to count the minimum number
// of 0s required to be removed to
// maximize the longest substring of 1s
static void minNumZeros(string str)
{
     
    // Stores leftmost and rightmost
    // indices consisting of 1
    int left = int.MaxValue;
    int right = int.MinValue;
 
    // Stores the count of 0s
    // between left and right
    int count = 0;
 
    // Traverse the string str
    for(int i = 0; i < str.Length; i++)
    {
         
        // If the current character is 1
        if (str[i] == '1')
        {
             
            // Update leftmost and rightmost
            // index consisting of 1
            left = Math.Min(i, left);
            right = Math.Max(right, i);
        }
    }
 
    // If string consists only of 0s
    if (left == int.MaxValue)
    {
        Console.WriteLine("0");
        return;
    }
 
    // Count the number of 0s
    // between left and right
    for(int i = left; i < right; i++)
    {
        if (str[i] == '0')
        {
            count++;
        }
    }
 
    // Print the result
    Console.WriteLine(count);
}
 
// Driver Code
static public void Main()
{
    string str = "010011";
     
    minNumZeros(str);
}
}
 
// This code is contributed by Dharanendra L V

Javascript

<script>
    // javascript program for the above approach
    // Function to count the minimum number
    // of 0s required to be removed to
    // maximize the longest substring of 1s
    function minNumZeros(str)
    {
     
        // Stores leftmost and rightmost
        // indices consisting of 1
        let left = Number.MAX_VALUE, right = Number.MIN_VALUE;
 
        // Stores the count of 0s
        // between left and right
        let count = 0;
 
        // Traverse the string str
        for (let i = 0; i < str.length; i++) {
 
            // If the current character is 1
            if (str[i] == '1') {
 
                // Update leftmost and rightmost
                // index consisting of 1
                left = Math.min(i, left);
                right = Math.max(right, i);
            }
        }
 
        // If string consists only of 0s
        if (left == Number.MAX_VALUE) {
            document.write("0");
            return;
        }
 
        // Count the number of 0s
        // between left and right
        for (let i = left; i < right; i++) {
 
            if (str[i] == '0') {
                count++;
            }
        }
 
        // Print the result
        document.write(count);
    }
 
    // Driver Code
 
    let str = "010011";
    minNumZeros(str);
 
// This code is contributed by vaibhavrabadiya117.
</script>
Producción: 

2

 

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

Publicación traducida automáticamente

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