Lexicographically largest string formed from the characters in range L and R | C ++ program to print the lexicographically largest string that can be formed from the characters in range L and R ; Function to return the lexicographically largest string ; hash array ; make 0 - based indexing ; iterate and count frequencies of character ; ans string ; iterate in frequency array ; add til all characters are added ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string printLargestString ( string s , int l , int r ) { int freq [ 26 ] = { 0 } ; l -- ; r -- ; for ( int i = min ( l , r ) ; i <= max ( l , r ) ; i ++ ) { freq [ s [ i ] - ' a ' ] ++ ; } string ans = " " ; for ( int i = 25 ; i >= 0 ; i -- ) { while ( freq [ i ] ) { ans += char ( ' a ' + i ) ; freq [ i ] -- ; } } return ans ; } int main ( ) { string s = " striver " ; int l = 3 , r = 5 ; cout << printLargestString ( s , l , r ) ; return 0 ; }