Dada una array de 0 y 1, encuentre la posición de 0 para ser reemplazada por 1 para obtener la secuencia continua más larga de 1. La complejidad de tiempo esperada es O(n) y el espacio auxiliar es O(1).
Ejemplos:
Input : arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1} Output : Index 9 Assuming array index starts from 0, replacing 0 with 1 at index 9 causes the maximum continuous sequence of 1s. Input : arr[] = {1, 1, 1, 1, 0} Output : Index 4
Hemos discutido una solución para este problema en una publicación anterior . En esta publicación se discuten dos métodos más para resolver el problema.
Método 1 (usando el conteo de unos en ambos lados del cero): la idea es contar el número de unos en ambos lados de cada cero. El índice requerido es el índice de cero que tiene un número máximo de unos a su alrededor. Las siguientes variables se utilizan en la implementación:
- leftCnt: Para almacenar el conteo de unos en el lado izquierdo del elemento actual cero bajo consideración.
- rightCnt: Para almacenar el conteo de unos en el lado derecho del elemento actual cero bajo consideración.
- maxIndex: índice de cero con un número máximo de unos a su alrededor.
- lastInd: índice del último elemento cero visto
- maxCnt: Recuento de unos si cero en el índice maxInd se reemplaza por uno.
Siga incrementando rightCnt hasta que uno esté presente en la array de entrada. Deje que el siguiente cero esté presente en el índice i. Compruebe si este elemento cero es el primer elemento cero o no. Es el primer elemento cero si lastInd no contiene ningún valor de índice válido. En ese caso, actualice lastInd con i. Ahora el valor de rightCnt es el número de ceros en el lado izquierdo de este cero. Así que leftCnt es igual a rightCnt y luego encuentra nuevamente el valor de rightCnt. Si el elemento cero actual no es el primer cero, entonces el número de unos alrededor del cero presente en el índice lastInd viene dado por leftCnt + rightCnt. maxCnt tomará el valor leftCnt + rightCnt + 1 y maxIndex = lastInd si este valor es menor que el valor actualmente en poder de maxCnt. Ahora rightCnt se convertirá en leftCnt para cero en el índice i y lastInd será igual a i. Nuevamente encuentre el valor de rightCnt, compare el número de unos con maxcnt y actualice maxCnt y maxIndex en consecuencia. Repita este procedimiento para cada elemento cero subsiguiente de la array. Observe que lastInd almacena el índice de cero para el cual se calculan leftCnt y rightCnt actuales. El índice requerido de cero para ser reemplazado por uno se almacena en maxIndex.
A continuación se muestra la implementación del algoritmo anterior.
C++
// C++ program to find index of zero // to be replaced by one to get longest // continuous sequence of ones. #include <bits/stdc++.h> using namespace std; // Returns index of 0 to be replaced // with 1 to get longest continuous // sequence of 1s. If there is no 0 // in array, then it returns -1. int maxOnesIndex(bool arr[], int n) { int i = 0; // To store count of ones on left // side of current element zero int leftCnt = 0; // To store count of ones on right // side of current element zero int rightCnt = 0; // Index of zero with maximum number // of ones around it. int maxIndex = -1; // Index of last zero element seen int lastInd = -1; // Count of ones if zero at index // maxInd is replaced by one. int maxCnt = 0; while (i < n) { // Keep incrementing count until // current element is 1. if (arr[i]) { rightCnt++; } else { // If current zero element // is not first zero element, // then count number of ones // obtained by replacing zero at // index lastInd. Update maxCnt // and maxIndex if required. if (lastInd != -1) { if (rightCnt + leftCnt + 1 > maxCnt) { maxCnt = leftCnt + rightCnt + 1; maxIndex = lastInd; } } lastInd = i; leftCnt = rightCnt; rightCnt = 0; } i++; } // Find number of ones in continuous // sequence when last zero element is // replaced by one. if (lastInd != -1) { if (leftCnt + rightCnt + 1 > maxCnt) { maxCnt = leftCnt + rightCnt + 1; maxIndex = lastInd; } } return maxIndex; } // Driver function int main() { bool arr[] = { 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 }; // bool arr[] = {1, 1, 1, 1, 0}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Index of 0 to be replaced is " << maxOnesIndex(arr, n); return 0; }
Java
// Java program to find index of zero // to be replaced by one to get longest // continuous sequence of ones. class GFG { // Returns index of 0 to be replaced // with 1 to get longest continuous // sequence of 1s. If there is no 0 // in array, then it returns -1. static int maxOnesIndex(boolean arr[], int n) { int i = 0; // To store count of ones on left // side of current element zero int leftCnt = 0; // To store count of ones on right // side of current element zero int rightCnt = 0; // Index of zero with maximum number // of ones around it. int maxIndex = -1; // Index of last zero element seen int lastInd = -1; // Count of ones if zero at index // maxInd is replaced by one. int maxCnt = 0; while (i < n) { // Keep incrementing count until // current element is 1. if (arr[i]) { rightCnt++; } else { // If current zero element // is not first zero element, // then count number of ones // obtained by replacing zero at // index lastInd. Update maxCnt // and maxIndex if required. if (lastInd != -1) { if (rightCnt + leftCnt + 1 > maxCnt) { maxCnt = leftCnt + rightCnt + 1; maxIndex = lastInd; } } lastInd = i; leftCnt = rightCnt; rightCnt = 0; } i++; } // Find number of ones in continuous // sequence when last zero element is // replaced by one. if (lastInd != -1) { if (leftCnt + rightCnt + 1 > maxCnt) { maxCnt = leftCnt + rightCnt + 1; maxIndex = lastInd; } } return maxIndex; } // Driver function public static void main(String[] args) { boolean arr[] = {true, true, false, false, true, false, true, true, true, false, true, true, true,}; int n = arr.length; System.out.println("Index of 0 to be replaced is " + maxOnesIndex(arr, n)); } } //This code contribute by Shikha Singh
Python3
# Python3 program to find index of zero # to be replaced by one to get longest # continuous sequence of ones. # Returns index of 0 to be replaced # with 1 to get longest continuous # sequence of 1s. If there is no 0 # in array, then it returns -1. def maxOnesIndex(arr, n): i = 0 # To store count of ones on left # side of current element zero leftCnt = 0 # To store count of ones on right # side of current element zero rightCnt = 0 # Index of zero with maximum number # of ones around it. maxIndex = -1 # Index of last zero element seen lastInd = -1 # Count of ones if zero at index # maxInd is replaced by one. maxCnt = 0 while i < n: # Keep incrementing count until # current element is 1. if arr[i] == 1: rightCnt += 1 else: # If current zero element # is not first zero element, # then count number of ones # obtained by replacing zero at # index lastInd. Update maxCnt # and maxIndex if required. if lastInd != -1: if rightCnt + leftCnt + 1 > maxCnt: maxCnt = leftCnt + rightCnt + 1 maxIndex = lastInd lastInd = i leftCnt = rightCnt rightCnt = 0 i += 1 # Find number of ones in continuous # sequence when last zero element is # replaced by one. if lastInd != -1: if leftCnt + rightCnt + 1 > maxCnt: maxCnt = leftCnt + rightCnt + 1 maxIndex = lastInd return maxIndex # Driver code if __name__ == "__main__": arr = [1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1] n = len(arr) print("Index of 0 to be replaced is", maxOnesIndex(arr, n)) # This code is contributed # by Rituraj Jain
C#
// C# program to find index of zero // to be replaced by one to get longest // continuous sequence of ones. using System; public class GFG{ // Returns index of 0 to be replaced // with 1 to get longest continuous // sequence of 1s. If there is no 0 // in array, then it returns -1. static int maxOnesIndex(bool []arr, int n) { int i = 0; // To store count of ones on left // side of current element zero int leftCnt = 0; // To store count of ones on right // side of current element zero int rightCnt = 0; // Index of zero with maximum number // of ones around it. int maxIndex = -1; // Index of last zero element seen int lastInd = -1; // Count of ones if zero at index // maxInd is replaced by one. int maxCnt = 0; while (i < n) { // Keep incrementing count until // current element is 1. if (arr[i]) { rightCnt++; } else { // If current zero element // is not first zero element, // then count number of ones // obtained by replacing zero at // index lastInd. Update maxCnt // and maxIndex if required. if (lastInd != -1) { if (rightCnt + leftCnt + 1 > maxCnt) { maxCnt = leftCnt + rightCnt + 1; maxIndex = lastInd; } } lastInd = i; leftCnt = rightCnt; rightCnt = 0; } i++; } // Find number of ones in continuous // sequence when last zero element is // replaced by one. if (lastInd != -1) { if (leftCnt + rightCnt + 1 > maxCnt) { maxCnt = leftCnt + rightCnt + 1; maxIndex = lastInd; } } return maxIndex; } // Driver function static public void Main (){ bool []arr = {true, true, false, false, true, false, true, true, true, false, true, true, true,}; int n = arr.Length; Console.WriteLine("Index of 0 to be replaced is " + maxOnesIndex(arr, n)); } } //This code contribute by ajit
PHP
<?php // PHP program to find index of zero // to be replaced by one to get longest // continuous sequence of ones. // Returns index of 0 to be replaced // with 1 to get longest continuous // sequence of 1s. If there is no 0 // in array, then it returns -1. function maxOnesIndex($arr, $n) { $i = 0; // To store count of ones on left // side of current element zero $leftCnt = 0; // To store count of ones on right // side of current element zero $rightCnt = 0; // Index of zero with maximum number // of ones around it. $maxIndex = -1; // Index of last zero element seen $lastInd = -1; // Count of ones if zero at index // maxInd is replaced by one. $maxCnt = 0; while ($i < $n) { // Keep incrementing count until // current element is 1. if ($arr[$i]) { $rightCnt++; } else { // If current zero element // is not first zero element, // then count number of ones // obtained by replacing zero at // index lastInd. Update maxCnt // and maxIndex if required. if ($lastInd != -1) { if ($rightCnt + $leftCnt + 1 > $maxCnt) { $maxCnt = $leftCnt + $rightCnt + 1; $maxIndex = $lastInd; } } $lastInd = $i; $leftCnt = $rightCnt; $rightCnt = 0; } $i++; } // Find number of ones in continuous // sequence when last zero element is // replaced by one. if ($lastInd != -1) { if ($leftCnt + $rightCnt + 1 > $maxCnt) { $maxCnt = $leftCnt + $rightCnt + 1; $maxIndex = $lastInd; } } return $maxIndex; } // Driver Code $arr = array(1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1); // bool arr[] = {1, 1, 1, 1, 0}; $n = sizeof($arr); echo "Index of 0 to be replaced is ". maxOnesIndex($arr, $n); // This code is contributed // by Akanksha Rai ?>
Javascript
<script> // Javascript program to find index of zero // to be replaced by one to get longest // continuous sequence of ones. // Returns index of 0 to be replaced // with 1 to get longest continuous // sequence of 1s. If there is no 0 // in array, then it returns -1. function maxOnesIndex(arr, n) { var i = 0; // To store count of ones on left // side of current element zero var leftCnt = 0; // To store count of ones on right // side of current element zero var rightCnt = 0; // Index of zero with maximum number // of ones around it. var maxIndex = -1; // Index of last zero element seen var lastInd = -1; // Count of ones if zero at index // maxInd is replaced by one. var maxCnt = 0; while (i < n) { // Keep incrementing count until // current element is 1. if (arr[i]) { rightCnt++; } else { // If current zero element // is not first zero element, // then count number of ones // obtained by replacing zero at // index lastInd. Update maxCnt // and maxIndex if required. if (lastInd != -1) { if (rightCnt + leftCnt + 1 > maxCnt) { maxCnt = leftCnt + rightCnt + 1; maxIndex = lastInd; } } lastInd = i; leftCnt = rightCnt; rightCnt = 0; } i++; } // Find number of ones in continuous // sequence when last zero element is // replaced by one. if (lastInd != -1) { if (leftCnt + rightCnt + 1 > maxCnt) { maxCnt = leftCnt + rightCnt + 1; maxIndex = lastInd; } } return maxIndex; } // Driver function var arr = [ 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 ]; // bool arr[] = {1, 1, 1, 1, 0}; var n = arr.length; document.write( "Index of 0 to be replaced is " + maxOnesIndex(arr, n)); // This code is contributed by itsok. </script>
Producción:
Index of 0 to be replaced is 9
Complejidad de tiempo: O(n)
Espacio auxiliar: O(1)
Método 2 (usando ventana deslizante):Se utiliza una ventana deslizante para encontrar el número de unos en la secuencia continua más larga obtenida reemplazando un cero. La idea es seguir incrementando el punto final de la ventana deslizante hasta que uno esté presente en la array de entrada. Cuando se encuentre un cero, verifique si es el primer elemento cero o no. Si es el primer elemento cero, la ventana deslizante se expande aún más. Si no es así, encuentre la longitud de la ventana deslizante. Esta longitud es el número de unos obtenidos reemplazando el elemento cero presente en la ventana deslizante. Tenga en cuenta que esta longitud da el número de unos obtenidos al reemplazar el elemento cero anterior y no el elemento cero actual. Para el elemento cero actual, el punto de inicio de la ventana deslizante es el índice junto al índice del elemento cero anterior.
A continuación se muestra la implementación del algoritmo anterior.
C++
// C++ program to find index of zero // to be replaced by one to get longest // continuous sequence of ones. #include <bits/stdc++.h> using namespace std; // Returns index of 0 to be replaced // with 1 to get longest continuous // sequence of 1s. If there is no 0 // in array, then it returns -1. int maxOnesIndex(bool arr[], int n) { // To store starting point of // sliding window. int start = 0; // To store ending point of // sliding window. int end = 0; // Index of zero with maximum number // of ones around it. int maxIndex = -1; // Index of last zero element seen int lastInd = -1; // Count of ones if zero at index // maxInd is replaced by one. int maxCnt = 0; while (end < n) { // Keep increasing ending point // of sliding window until one is // present in input array. while (end < n && arr[end]) { end++; } // If this is not first zero element // then number of ones obtained by // replacing zero at lastInd is // equal to length of window. // Compare this with maximum number // of ones in a previous window so far. if (maxCnt < end - start && lastInd != -1) { maxCnt = end - start; maxIndex = lastInd; } // The new starting point of next window // is from index position next to last // zero which is stored in lastInd. start = lastInd + 1; lastInd = end; end++; } // For the case when only one zero is // present in input array and is at // last position. if (maxCnt < end - start && lastInd != -1) { maxCnt = end - start; maxIndex = lastInd; } return maxIndex; } // Driver function int main() { bool arr[] = { 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 }; // bool arr[] = {1, 1, 1, 1, 0}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Index of 0 to be replaced is " << maxOnesIndex(arr, n); return 0; }
Java
// Java program to find index of zero // to be replaced by one to get longest // continuous sequence of ones. public class GFG { // Returns index of 0 to be replaced // with 1 to get longest continuous // sequence of 1s. If there is no 0 // in array, then it returns -1. static int maxOnesIndex(boolean arr[], int n) { // To store starting point of // sliding window. int start = 0; // To store ending point of // sliding window. int end = 0; // Index of zero with maximum number // of ones around it. int maxIndex = -1; // Index of last zero element seen int lastInd = -1; // Count of ones if zero at index // maxInd is replaced by one. int maxCnt = 0; while (end < n) { // Keep increasing ending point // of sliding window until one is // present in input array. while (end < n && arr[end]) { end++; } // If this is not first zero element // then number of ones obtained by // replacing zero at lastInd is // equal to length of window. // Compare this with maximum number // of ones in a previous window so far. if (maxCnt < end - start && lastInd != -1) { maxCnt = end - start; maxIndex = lastInd; } // The new starting point of next window // is from index position next to last // zero which is stored in lastInd. start = lastInd + 1; lastInd = end; end++; } // For the case when only one zero is // present in input array and is at // last position. if (maxCnt < end - start && lastInd != -1) { maxCnt = end - start; maxIndex = lastInd; } return maxIndex; } // Driver function static public void main(String[] args) { boolean arr[] = {true, true, false, false, true, false, true, true, true, false, true, true, true,}; // bool arr[] = {1, 1, 1, 1, 0}; int n = arr.length; System.out.println("Index of 0 to be replaced is " + maxOnesIndex(arr, n)); } } // This code is contributed by Rajput-Ji
Python3
# Python3 program to find index of zero # to be replaced by one to get longest # continuous sequence of ones. # Returns index of 0 to be replaced # with 1 to get longest continuous # sequence of 1s. If there is no 0 # in array, then it returns -1. def maxOnesIndex(arr, n): # To store starting point of # sliding window. start = 0 # To store ending point of # sliding window. end = 0 # Index of zero with maximum # number of ones around it. maxIndex = -1 # Index of last zero element seen lastInd = -1 # Count of ones if zero at index # maxInd is replaced by one. maxCnt = 0 while (end < n) : # Keep increasing ending point # of sliding window until one is # present in input array. while (end < n and arr[end]) : end += 1 # If this is not first zero element # then number of ones obtained by # replacing zero at lastInd is # equal to length of window. #Compare this with maximum number # of ones in a previous window so far. if (maxCnt < end - start and lastInd != -1) : maxCnt = end - start maxIndex = lastInd # The new starting point of next window # is from index position next to last # zero which is stored in lastInd. start = lastInd + 1 lastInd = end end += 1 # For the case when only one zero is # present in input array and is at # last position. if (maxCnt < end - start and lastInd != -1) : maxCnt = end - start maxIndex = lastInd return maxIndex # Driver Code if __name__ == "__main__": arr = [1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 ] # arr= [1, 1, 1, 1, 0] n = len(arr) print ("Index of 0 to be replaced is ", maxOnesIndex(arr, n)) # This code is contributed by ChitraNayal
C#
using System; // c# program to find index of zero // to be replaced by one to get longest // continuous sequence of ones. public class GFG { // Returns index of 0 to be replaced // with 1 to get longest continuous // sequence of 1s. If there is no 0 // in array, then it returns -1. public static int maxOnesIndex(bool[] arr, int n) { // To store starting point of // sliding window. int start = 0; // To store ending point of // sliding window. int end = 0; // Index of zero with maximum number // of ones around it. int maxIndex = -1; // Index of last zero element seen int lastInd = -1; // Count of ones if zero at index // maxInd is replaced by one. int maxCnt = 0; while (end < n) { // Keep increasing ending point // of sliding window until one is // present in input array. while (end < n && arr[end]) { end++; } // If this is not first zero element // then number of ones obtained by // replacing zero at lastInd is // equal to length of window. // Compare this with maximum number // of ones in a previous window so far. if (maxCnt < end - start && lastInd != -1) { maxCnt = end - start; maxIndex = lastInd; } // The new starting point of next window // is from index position next to last // zero which is stored in lastInd. start = lastInd + 1; lastInd = end; end++; } // For the case when only one zero is // present in input array and is at // last position. if (maxCnt < end - start && lastInd != -1) { maxCnt = end - start; maxIndex = lastInd; } return maxIndex; } // Driver function public static void Main(string[] args) { bool[] arr = new bool[] {true, true, false, false, true, false, true, true, true, false, true, true, true}; // bool arr[] = {1, 1, 1, 1, 0}; int n = arr.Length; Console.WriteLine("Index of 0 to be replaced is " + maxOnesIndex(arr, n)); } } // This code is contributed by Shrikant13
PHP
<?php // PHP program to find index of zero // to be replaced by one to get longest // continuous sequence of ones. // Returns index of 0 to be replaced // with 1 to get longest continuous // sequence of 1s. If there is no 0 // in array, then it returns -1. function maxOnesIndex($arr, $n) { // To store starting point of // sliding window. $start = 0; // To store ending point of // sliding window. $end = 0; // Index of zero with maximum // number of ones around it. $maxIndex = -1; // Index of last zero element seen $lastInd = -1; // Count of ones if zero at index // maxInd is replaced by one. $maxCnt = 0; while ($end < $n) { // Keep increasing ending point // of sliding window until one is // present in input array. while ($end < $n && $arr[$end]) { $end++; } // If this is not first zero element // then number of ones obtained by // replacing zero at lastInd is // equal to length of window. // Compare this with maximum number // of ones in a previous window so far. if ($maxCnt < $end - $start && $lastInd != -1) { $maxCnt = $end - $start; $maxIndex = $lastInd; } // The new starting point of next window // is from index position next to last // zero which is stored in lastInd. $start = $lastInd + 1; $lastInd = $end; $end++; } // For the case when only one zero is // present in input array and is at // last position. if ($maxCnt < $end - $start && $lastInd != -1) { $maxCnt = $end - $start; $maxIndex = $lastInd; } return $maxIndex; } // Driver Code $arr = array( 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 ); // bool arr[] = {1, 1, 1, 1, 0}; $n = sizeof($arr); echo "Index of 0 to be replaced is ", maxOnesIndex($arr, $n); // This code is contributed // by Sach_Code ?>
Javascript
<script> // Javascript program to find index of zero // to be replaced by one to get longest // continuous sequence of ones. // Returns index of 0 to be replaced // with 1 to get longest continuous // sequence of 1s. If there is no 0 // in array, then it returns -1. function maxOnesIndex( arr, n) { // To store starting point of // sliding window. var start = 0; // To store ending point of // sliding window. var end = 0; // Index of zero with maximum number // of ones around it. var maxIndex = -1; // Index of last zero element seen var lastInd = -1; // Count of ones if zero at index // maxInd is replaced by one. var maxCnt = 0; while (end < n) { // Keep increasing ending point // of sliding window until one is // present in input array. while (end < n && arr[end]) { end++; } // If this is not first zero element // then number of ones obtained by // replacing zero at lastInd is // equal to length of window. // Compare this with maximum number // of ones in a previous window so far. if (maxCnt < end - start && lastInd != -1) { maxCnt = end - start; maxIndex = lastInd; } // The new starting point of next window // is from index position next to last // zero which is stored in lastInd. start = lastInd + 1; lastInd = end; end++; } // For the case when only one zero is // present in input array and is at // last position. if (maxCnt < end - start && lastInd != -1) { maxCnt = end - start; maxIndex = lastInd; } return maxIndex; } // Driver function var arr = [ 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 ]; // bool arr[] = {1, 1, 1, 1, 0}; var n = arr.length; document.write( "Index of 0 to be replaced is " + maxOnesIndex(arr, n)); </script>
Producción:
Index of 0 to be replaced is 9
Complejidad temporal: O(n)
Espacio auxiliar: O(1)