Minimum flips to make all 1 s in right and 0 s in left | Java program to implement the above approach ; Function to find the minimum count of flips required to make all 1 s on the right and all 0 s on the left of the given string ; Stores length of str ; Store count of 0 s in the string ; Traverse the string ; If current character is 0 ; Update zeros ; If count of 0 s in the string is 0 or n ; Store minimum count of flips required to make all 0 s on the left and 1 s on the right ; Stores count of 1 s on the left side of each index ; Stores count of flips required to make all 0 s on the left and 1 s on the right ; Traverse the string ; If current character is 1 ; Update currOnes ; Update flips ; Update the minimum count of flips ; Driver code
import java . io . * ; class GFG { public static int minimumCntOfFlipsRequired ( String str ) { int n = str . length ( ) ; int zeros = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == '0' ) { zeros ++ ; } } if ( zeros == 0 zeros == n ) { return 0 ; } int minFlips = Integer . MAX_VALUE ; int currOnes = 0 ; int flips ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == '1' ) { currOnes ++ ; } flips = currOnes + ( zeros - ( i + 1 - currOnes ) ) ; minFlips = Math . min ( minFlips , flips ) ; } return minFlips ; } public static void main ( String [ ] args ) { String s1 = "100101" ; System . out . println ( minimumCntOfFlipsRequired ( s1 ) ) ; } }