Minimize cost to make all characters of a Binary String equal to '1' by reversing or flipping characters of substrings | Java program for the above approach ; Function to calculate minimum cost to convert all the characters of S to '1' ; Stores the result ; Stores the number of groups that have 0 as characters ; Traverse the string S ; If current character is '0' ; If count is greater than 0 ; Set the count to 0 ; If the last few consecutive characters are '0' ; If string contains all characters as '1' ; Minimum Cost ; Driver Code ; Given Input ; Function Call
class GFG { static void MinimumCost ( String S , int A , int B ) { int count = 0 ; int group = 0 ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) { if ( S . charAt ( i ) == '0' ) { count += 1 ; } else { if ( count > 0 ) { group += 1 ; } count = 0 ; } } if ( count > 0 ) group += 1 ; if ( group == 0 ) { System . out . println ( 0 ) ; } else { System . out . print ( Math . min ( A , B ) * ( group - 1 ) + B ) ; } } public static void main ( String args [ ] ) { int A = 1 ; int B = 5 ; String S = "01100" ; MinimumCost ( S , A , B ) ; } }