Find zeroes to be flipped so that number of consecutive 1 's is maximized | Java to find positions of zeroes flipping which produces maximum number of consecutive 1 's ; m is maximum of number zeroes allowed to flip ; Left and right indexes of current window ; Left index and size of the widest window ; Count of zeroes in current window ; While right boundary of current window doesn 't cross  right end ; If zero count of current window is less than m , widen the window toward right ; If zero count of current window is more than m , reduce the window from left ; Update widest window if this window size is more ; Print positions of zeroes in the widest window ; Driver method to test the above function
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 ) ; } }