Count of 0 s to be flipped to make any two adjacent 1 s at least K 0 s apart | Function to find the count of 0 s to be flipped ; Loop traversal to mark K adjacent positions to the right of already existing 1 s . ; Loop traversal to mark K adjacent positions to the left of already existing 1 s . ; Loop to count the maximum number of 0 s that will be replaced by 1 s ; Driver code
function count ( k , s ) { var ar = Array ( s . length ) . fill ( 0 ) ; var end = 0 ; var i , j ; for ( i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == ' ' ) { for ( j = i ; j < s . length && j <= i + k ; j ++ ) { ar [ j ] = - 1 ; end = j ; } i = end ; } } end = 0 ; for ( i = s . length - 1 ; i >= 0 ; i -- ) { if ( s [ i ] == ' ' ) { for ( j = i ; j >= 0 && j >= i - k ; j -- ) { ar [ j ] = - 1 ; end = j ; } i = end ; } } var ans = 0 ; end = 0 ; var g ; for ( j = 0 ; j < s . length ; j ++ ) { if ( ar [ j ] == 0 ) { ans ++ ; for ( g = j ; g <= j + k && g < s . length ; g ++ ) { ar [ g ] = - 1 ; end = g ; } j = end - 1 ; } } return ans ; } var K = 2 ; var s = " " ; document . write ( count ( K , s ) ) ;