Minimum non | Java program for above approach ; Function to find minimum flips required to remove all 0 s from a given binary string ; Length of given string ; Stores the indices of previous 0 s ; Stores the minimum operations ; Traverse string to find minimum operations to obtain required string ; Current character ; If current character is '0' ; Update temp1 with current index , if both temp variables are empty ; Update temp2 with current index , if temp1 contains prev index but temp2 is empty ; If temp1 is not empty ; Reset temp1 to - 1 ; Increase ans ; If temp2 is not empty but temp1 is empty ; Reset temp2 to - 1 ; Increase ans ; If both temp variables are not empty ; Otherwise ; Return the answer ; Driver Code
import java . util . * ; class GFG { static int minOperation ( String s ) { int n = s . length ( ) ; int temp1 = - 1 , temp2 = - 1 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int curr = s . charAt ( i ) ; if ( curr == '0' ) { if ( temp1 == - 1 && temp2 == - 1 ) { temp1 = i ; } else if ( temp1 != - 1 && temp2 == - 1 && i - temp1 == 1 ) { temp2 = i ; } else if ( temp1 != - 1 ) { temp1 = - 1 ; ans ++ ; } else if ( temp1 == - 1 && temp2 != - 1 && i - temp2 != 1 ) { temp2 = - 1 ; ans ++ ; } } } if ( temp1 != - 1 && temp2 != - 1 ) { ans += 2 ; } else if ( temp1 != - 1 temp2 != - 1 ) { ans += 1 ; } return ans ; } public static void main ( String [ ] args ) { String s = "110010" ; System . out . println ( minOperation ( s ) ) ; } }