Make a given Binary String non | Java program for the above approach ; Function to return the length of smallest subsequence required to be removed to make the given string non - decreasing ; Length of the string ; Count of zeros and ones ; Traverse the string ; Count minimum removals to obtain strings of the form "00000 . . . . " or "11111 . . . " ; Increment count ; Remove 1 s and remaining 0 s ; Driver Code
import java . io . * ; class GFG { public static void min_length ( String str ) { int n = str . length ( ) ; int total_zeros = 0 ; int total_ones = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == '0' ) { total_zeros ++ ; } else { total_ones ++ ; } } int ans = Math . min ( total_zeros , total_ones ) ; int cur_zeros = 0 , cur_ones = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char x = str . charAt ( i ) ; if ( x == '0' ) { cur_zeros ++ ; } else { cur_ones ++ ; } ans = Math . min ( ans , cur_ones + ( total_zeros - cur_zeros ) ) ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String str = "10011" ; min_length ( str ) ; } }