text: Largest lexicographical string with at most K consecutive elements | C ++ code for the above approach ; Function to find the largest lexicographical string with given constraints . ; vector containing frequency of each character . ; assigning frequency to ; empty string of string class type ; loop to iterate over maximum priority first . ; if frequency is greater than or equal to k . ; temporary variable to operate in - place of k . ; concatenating with the resultant string ans . ; handling k case by adjusting with just smaller priority element . ; condition to verify if index j does have frequency greater than 0 ; ; if no such element is found than string can not be processed further . ; if frequency is greater than 0 and less than k . ; here we don 't need to fix K  consecutive element criteria. ; otherwise check for next possible element . ; Driver program
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll  long long int NEW_LINE string getLargestString ( string s , ll k ) { vector < int > frequency_array ( 26 , 0 ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { frequency_array [ s [ i ] - ' a ' ] ++ ; } string ans = " " ; for ( int i = 25 ; i >= 0 ; ) { if ( frequency_array [ i ] > k ) { int temp = k ; string st ( 1 , i + ' a ' ) ; while ( temp > 0 ) { ans += st ; temp -- ; } frequency_array [ i ] -= k ; int j = i - 1 ; while ( frequency_array [ j ] <= 0 && j >= 0 ) { j -- ; } if ( frequency_array [ j ] > 0 && j >= 0 ) { string str ( 1 , j + ' a ' ) ; ans += str ; frequency_array [ j ] -= 1 ; } else { break ; } } else if ( frequency_array [ i ] > 0 ) { int temp = frequency_array [ i ] ; frequency_array [ i ] -= temp ; string st ( 1 , i + ' a ' ) ; while ( temp > 0 ) { ans += st ; temp -- ; } } else { i -- ; } } return ans ; } int main ( ) { string S = " xxxxzza " ; int k = 3 ; cout << getLargestString ( S , k ) << endl ; return 0 ; }