Find zeroes to be flipped so that number of consecutive 1’s is maximized
Last Updated :
06 Mar, 2024
Given a binary array and an integer m, find the position of zeroes flipping which creates maximum number of consecutive 1’s in array.
Examples :
Input: arr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1}
m = 2
Output: 5 7
We are allowed to flip maximum 2 zeroes. If we flip
arr[5] and arr[7], we get 8 consecutive 1's which is
maximum possible under given constraints
Input: arr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1}
m = 1
Output: 7
We are allowed to flip maximum 1 zero. If we flip
arr[7], we get 5 consecutive 1's which is maximum
possible under given constraints.
Input: arr[] = {0, 0, 0, 1}
m = 4
Output: 0 1 2
Since m is more than number of zeroes, we can flip
all zeroes.
A Simple Solution is to consider every subarray by running two loops. For every subarray, count number of zeroes in it. Return the maximum size subarray with m or less zeroes. Time Complexity of this solution is O(n2).
A Better Solution is to use auxiliary space to solve the problem in O(n) time.
For all positions of 0’s calculate left[] and right[] which defines the number of consecutive 1’s to the left of i and right of i respectively.
For example, for arr[] = {1, 1, 0, 1, 1, 0, 0, 1, 1, 1} and m = 1, left[2] = 2 and right[2] = 2, left[5] = 2 and right[5] = 0, left[6] = 0 and right[6] = 3.
left[] and right[] can be filled in O(n) time by traversing array once and keeping track of last seen 1 and last seen 0. While filling left[] and right[], we also store indexes of all zeroes in a third array say zeroes[]. For above example, this third array stores {2, 5, 6}
Now traverse zeroes[] and for all consecutive m entries in this array, compute the sum of 1s that can be produced. This step can be done in O(n) using left[] and right[].
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > maximized_one( int arr[], int n, int m)
{
int left[n] = { 0 };
int right[n] = { 0 };
vector< int > zero_pos;
int count = 0;
int previous_index_of_zero = -1;
for ( int i = 0; i < n; i++) {
if (arr[i]) {
count++;
}
else {
left[i] = count;
zero_pos.push_back(i);
if (previous_index_of_zero != i
&& previous_index_of_zero != -1) {
right[previous_index_of_zero] = count;
}
count = 0;
previous_index_of_zero = i;
}
}
right[previous_index_of_zero] = count;
int max_one = -1;
vector< int > result_index;
int i = 0;
while (i <= (zero_pos.size()) - m) {
int temp = 0;
vector< int > index;
for ( int c = 0; c < m; c++) {
temp += left[zero_pos[i + c]]
+ right[zero_pos[i + c]] + 1;
index.push_back(zero_pos[i + c]);
}
temp = temp - (m - 1);
if (temp > max_one) {
max_one = temp;
result_index = index;
}
i += 1;
}
return result_index;
}
int main()
{
int arr[] = { 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1 };
int m = 2;
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Index of zeroes that are flipped: " ;
vector< int > result_index = maximized_one(arr, n, m);
for ( auto i : result_index) {
cout << i << " " ;
}
return 0;
}
|
Java
import java.util.*;
class GFG{
static Vector<Integer> maximized_one( int arr[], int n, int m)
{
int left[] = new int [n];
int right[] = new int [n];
Vector<Integer> zero_pos = new Vector<>();
int count = 0 ;
int previous_index_of_zero = - 1 ;
for ( int i = 0 ; i < n; i++) {
if (arr[i]!= 0 ) {
count++;
}
else {
left[i] = count;
zero_pos.add(i);
if (previous_index_of_zero != i
&& previous_index_of_zero != - 1 ) {
right[previous_index_of_zero] = count;
}
count = 0 ;
previous_index_of_zero = i;
}
}
right[previous_index_of_zero] = count;
int max_one = - 1 ;
Vector<Integer> result_index = new Vector<>();
int i = 0 ;
while (i <= (zero_pos.size()) - m) {
int temp = 0 ;
Vector<Integer> index = new Vector<>();
for ( int c = 0 ; c < m; c++) {
temp += left[zero_pos.elementAt(i + c)]
+ right[zero_pos.elementAt(i + c)] + 1 ;
index.add(zero_pos.elementAt(i + c));
}
temp = temp - (m - 1 );
if (temp > max_one) {
max_one = temp;
result_index = index;
}
i += 1 ;
}
return result_index;
}
public static void main(String[] args)
{
int arr[] = { 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 1 , 1 };
int m = 2 ;
int n = arr.length;
System.out.print( "Index of zeroes that are flipped: [" );
Vector<Integer> result_index = maximized_one(arr, n, m);
for ( int i : result_index) {
System.out.print(i+ " " );
}
System.out.print( "]" );
}
}
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static List< int > maximized_one( int []arr, int n, int m)
{
int []left = new int [n];
int []right = new int [n];
List< int > zero_pos = new List< int >();
int count = 0;
int previous_index_of_zero = -1;
for ( int j = 0; j < n; j++) {
if (arr[j] != 0) {
count++;
}
else {
left[j] = count;
zero_pos.Add(j);
if (previous_index_of_zero != j
&& previous_index_of_zero != -1) {
right[previous_index_of_zero] = count;
}
count = 0;
previous_index_of_zero = j;
}
}
right[previous_index_of_zero] = count;
int max_one = -1;
List< int > result_index = new List< int >();
int i = 0;
while (i <= (zero_pos.Count) - m) {
int temp = 0;
List< int > index = new List< int >();
for ( int c = 0; c < m; c++) {
temp += left[zero_pos[i + c]]
+ right[zero_pos[i + c]] + 1;
index.Add(zero_pos[i + c]);
}
temp = temp - (m - 1);
if (temp > max_one) {
max_one = temp;
result_index = index;
}
i += 1;
}
return result_index;
}
public static void Main(String[] args)
{
int []arr = { 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1 };
int m = 2;
int n = arr.Length;
Console.Write( "Index of zeroes that are flipped: [" );
List< int > result_index = maximized_one(arr, n, m);
foreach ( int i in result_index) {
Console.Write(i+ " " );
}
Console.Write( "]" );
}
}
|
Javascript
<script>
function maximized_one(arr, n, m)
{
var left = Array(n).fill(0);
var right = Array(n).fill(0);
var zero_pos = new Array();
var count = 0;
var previous_index_of_zero = -1;
for ( var i = 0; i < n; i++) {
if (arr[i] != 0) {
count++;
} else {
left[i] = count;
zero_pos.push(i);
if (previous_index_of_zero != i && previous_index_of_zero != -1) {
right[previous_index_of_zero] = count;
}
count = 0;
previous_index_of_zero = i;
}
}
right[previous_index_of_zero] = count;
var max_one = -1;
var result_index = Array();
var i = 0;
while (i <= (zero_pos.length) - m) {
var temp = 0;
var index = Array();
for ( var c = 0; c < m; c++)
{
temp += left[zero_pos[i + c]] + right[zero_pos[i + c]] + 1;
index.push(zero_pos[i + c]);
}
temp = temp - (m - 1);
if (temp > max_one) {
max_one = temp;
result_index = index;
}
i += 1;
}
return result_index;
}
var arr = [ 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1 ];
var m = 2;
var n = arr.length;
document.write( "Index of zeroes that are flipped: [" );
var result_index = maximized_one(arr, n, m);
for ( var i = 0; i < result_index.length; i++) {
document.write(result_index[i] + " " );
}
document.write( "]" );
</script>
|
Python3
def maximized_one(arr,n,m):
left = [ 0 ] * n
right = [ 0 ] * n
zero_pos = []
count = 0
previous_index_of_zero = - 1
for i in range (n):
if arr[i] = = 1 :
count + = 1
if arr[i] = = 0 :
left[i] = count
zero_pos.append(i)
if previous_index_of_zero ! = i and previous_index_of_zero! = - 1 :
right[previous_index_of_zero] = count
count = 0
previous_index_of_zero = i
right[previous_index_of_zero] = count
max_one = - 1
result_index = 0
i = 0
while (i< = len (zero_pos) - m):
temp = 0
index = []
for c in range (m):
temp + = left[zero_pos[i + c]] + right[zero_pos[i + c]] + 1
index.append(zero_pos[i + c])
temp = temp - (m - 1 )
if temp > max_one:
max_one = temp
result_index = index
i + = 1
return result_index
if __name__ = = '__main__' :
arr = [ 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 1 , 1 ]
n = len (arr)
m = 2
print ( 'Index of zeroes that are flipped: ' ,maximized_one(arr,n,m))
|
Output
Index of zeroes that are flipped: [5, 7]
Time Complexity: O(n)
Auxiliary Space: O(n)
An Efficient Solution can solve the problem in O(n) time and O(1) space. The idea is to use Sliding Window for the given array.
Let us use a window covering from index wL to index wR. Let the number of zeros inside the window be zeroCount. We maintain the window with at most m zeros inside.
The main steps are:
- While zeroCount is no more than m: expand the window to the right (wR++) and update the count zeroCount.
- While zeroCount exceeds m, shrink the window from left (wL++), update zeroCount;
- Update the widest window along the way. The positions of output zeros are inside the best window.
Below is the implementation of the idea.
C++
#include<bits/stdc++.h>
using namespace std;
void findZeroes( int arr[], int n, int m)
{
int wL = 0, wR = 0;
int bestL = 0, bestWindow = 0;
int zeroCount = 0;
while (wR < n)
{
if (zeroCount <= m)
{
if (arr[wR] == 0)
zeroCount++;
wR++;
}
if (zeroCount > m)
{
if (arr[wL] == 0)
zeroCount--;
wL++;
}
if ((wR-wL > bestWindow) && (zeroCount<=m))
{
bestWindow = wR-wL;
bestL = wL;
}
}
for ( int i=0; i<bestWindow; i++)
{
if (arr[bestL+i] == 0)
cout << bestL+i << " " ;
}
}
int main()
{
int arr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1};
int m = 2;
int n = sizeof (arr)/ sizeof (arr[0]);
cout << "Indexes of zeroes to be flipped are " ;
findZeroes(arr, n, m);
return 0;
}
|
Java
class Test
{
static int arr[] = new int []{ 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 1 };
static void findZeroes( int m)
{
int wL = 0 , wR = 0 ;
int bestL = 0 , bestWindow = 0 ;
int zeroCount = 0 ;
while (wR < arr.length)
{
if (zeroCount <= m)
{
if (arr[wR] == 0 )
zeroCount++;
wR++;
}
if (zeroCount > m)
{
if (arr[wL] == 0 )
zeroCount--;
wL++;
}
if ((wR-wL > bestWindow) && (zeroCount<=m))
{
bestWindow = wR-wL;
bestL = wL;
}
}
for ( int i= 0 ; i<bestWindow; i++)
{
if (arr[bestL+i] == 0 )
System.out.print(bestL+i + " " );
}
}
public static void main(String[] args)
{
int m = 2 ;
System.out.println( "Indexes of zeroes to be flipped are " );
findZeroes(m);
}
}
|
C#
using System;
class Test
{
static int []arr = new int []{1, 0, 0, 1, 1,
0, 1, 0, 1, 1};
static void findZeroes( int m)
{
int wL = 0, wR = 0;
int bestL = 0, bestWindow = 0;
int zeroCount = 0;
while (wR < arr.Length)
{
if (zeroCount <= m)
{
if (arr[wR] == 0)
zeroCount++;
wR++;
}
if (zeroCount > m)
{
if (arr[wL] == 0)
zeroCount--;
wL++;
}
if ((wR-wL > bestWindow) && (zeroCount<=m))
{
bestWindow = wR-wL;
bestL = wL;
}
}
for ( int i = 0; i < bestWindow; i++)
{
if (arr[bestL + i] == 0)
Console.Write(bestL + i + " " );
}
}
public static void Main(String[] args)
{
int m = 2;
Console.Write( "Indexes of zeroes to be flipped are " );
findZeroes(m);
}
}
|
Javascript
<script>
function findZeroes(arr, n, m) {
let wL = 0;
let wR = 0;
let bestL = 0;
let bestWindow = 0;
let zeroCount = 0;
while (wR < n) {
if (zeroCount <= m) {
if (arr[wR] == 0)
zeroCount++;
wR++;
}
if (zeroCount > m) {
if (arr[wL] == 0)
zeroCount--;
wL++;
}
if ((wR - wL > bestWindow) && (zeroCount <= m)) {
bestWindow = wR - wL;
bestL = wL;
}
}
for (let i = 0; i < bestWindow; i++) {
if (arr[bestL + i] == 0)
document.write(bestL + i + " " );
}
}
let arr = new Array(1, 0, 0, 1, 1, 0, 1, 0, 1, 1);
let m = 2;
let n = arr.length;
document.write( "Indexes of zeroes to be flipped are " );
findZeroes(arr, n, m);
</script>
|
PHP
<?php
function findZeroes( $arr , $n , $m )
{
$wL = 0;
$wR = 0;
$bestL = 0;
$bestWindow = 0;
$zeroCount = 0;
while ( $wR < $n )
{
if ( $zeroCount <= $m )
{
if ( $arr [ $wR ] == 0)
$zeroCount ++;
$wR ++;
}
if ( $zeroCount > $m )
{
if ( $arr [ $wL ] == 0)
$zeroCount --;
$wL ++;
}
if (( $wR - $wL > $bestWindow ) && ( $zeroCount <= $m ))
{
$bestWindow = $wR - $wL ;
$bestL = $wL ;
}
}
for ( $i = 0; $i < $bestWindow ; $i ++)
{
if ( $arr [ $bestL + $i ] == 0)
echo $bestL + $i . " " ;
}
}
$arr = array (1, 0, 0, 1, 1, 0, 1, 0, 1, 1);
$m = 2;
$n = sizeof( $arr )/sizeof( $arr [0]);
echo "Indexes of zeroes to be flipped are " ;
findZeroes( $arr , $n , $m );
return 0;
?>
|
Python3
def findZeroes(arr, n, m) :
wL = wR = 0
bestL = bestWindow = 0
zeroCount = 0
while wR < n:
if zeroCount < = m :
if arr[wR] = = 0 :
zeroCount + = 1
wR + = 1
if zeroCount > m :
if arr[wL] = = 0 :
zeroCount - = 1
wL + = 1
if (wR - wL > bestWindow) and (zeroCount< = m) :
bestWindow = wR - wL
bestL = wL
for i in range ( 0 , bestWindow):
if arr[bestL + i] = = 0 :
print (bestL + i, end = " " )
arr = [ 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 1 ]
m = 2
n = len (arr)
print ( "Indexes of zeroes to be flipped are" , end = " " )
findZeroes(arr, n, m)
|
Output
Indexes of zeroes to be flipped are 5 7
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...