Minimize flips to make binary string as all 1 s by flipping characters in substring of size K repeatedly | Java program for the above approach ; Function to find the minimum number of operations required to convert all the characters to 1 by flipping the substrings of size K ; Stores the minimum number of operations required ; Traverse the string S ; If the character is 0 ; Flip the substrings of size K starting from i ; Increment the minimum count of operations required ; After performing the operations check if string S contains any 0 s ; If S contains only 1 's ; Driver Code
public class GFG { static void minOperation ( String S , int K , int N ) { int min = 0 ; int i ; for ( i = 0 ; i < N ; i ++ ) { if ( S . charAt ( i ) == '0' && i + K <= N ) { for ( int j = i ; j < i + K ; j ++ ) { if ( S . charAt ( j ) == '1' ) S = S . substring ( 0 , j ) + '0' + S . substring ( j + 1 ) ; else S = S . substring ( 0 , j ) + '1' + S . substring ( j + 1 ) ; } min ++ ; } } for ( i = 0 ; i < N ; i ++ ) { if ( S . charAt ( i ) == '0' ) break ; } if ( i == N ) System . out . println ( min ) ; else System . out . println ( - 1 ) ; } public static void main ( String [ ] args ) { String S = "00010110" ; int K = 3 ; int N = S . length ( ) ; minOperation ( S , K , N ) ; } }