text: Lexicographically largest string possible by reversing substrings having even number of 1 s | C ++ program for the above approach ; Function to find the lexicographically maximum string by reversing substrings having even numbers of 1 s ; Store size of string ; Traverse the string ; Count the number of 1 s ; Stores the starting index ; Stores the end index ; Increment count , when 1 is encountered ; Traverse the remaining string ; Reverse the string from starting and end index ; Printing the string ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void lexicographicallyMax ( string s ) { int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; int beg = i ; int end = i ; if ( s [ i ] == '1' ) count ++ ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( s [ j ] == '1' ) count ++ ; if ( count % 2 == 0 && count != 0 ) { end = j ; break ; } } reverse ( s . begin ( ) + beg , s . begin ( ) + end + 1 ) ; } cout << s << " STRNEWLINE " ; } int main ( ) { string S = "0101" ; lexicographicallyMax ( S ) ; return 0 ; }