Largest lexicographical string with at most K consecutive elements | Java code for the above approach ; Function to find the largest lexicographical String with given constraints . ; Vector containing frequency of each character . ; Assigning frequency ; 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 code
import java . util . * ; class GFG { static String getLargestString ( String s , int k ) { int [ ] frequency_array = new int [ 26 ] ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { frequency_array [ s . charAt ( i ) - ' a ' ] ++ ; } String ans = " " ; for ( int i = 25 ; i >= 0 { if ( frequency_array [ i ] > k ) { int temp = k ; String st = String . valueOf ( ( char ) ( 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 = String . valueOf ( ( char ) ( 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 = String . valueOf ( ( char ) ( i + ' a ' ) ) ; while ( temp > 0 ) { ans += st ; temp -- ; } } else { i -- ; } } return ans ; } public static void main ( String [ ] args ) { String S = " xxxxzza " ; int k = 3 ; System . out . print ( getLargestString ( S , k ) ) ; } }