text: Lexicographically largest possible String after removal of K characters | Java program to implement the above approach ; Final result String ; If the current char exceeds the character at the top of the stack ; Remove from the end of the String ; Decrease k for the removal ; Insert current character ; Perform remaining K deletions from the end of the String ; Return the String ; Driver Code
code: class GFG { static String largestString ( String num , int k ) { String ans = " " ; for ( char i : num . toCharArray ( ) ) { while ( ans . length ( ) > 0 && ans . charAt ( ans . length ( ) - 1 ) < i && k > 0 ) { ans = ans . substring ( 0 , ans . length ( ) - 1 ) ; k -- ; } ans += i ; } while ( ans . length ( ) > 0 && k -- > 0 ) { ans = ans . substring ( 0 , ans . length ( ) - 1 ) ; } return ans ; } public static void main ( String [ ] args ) { String str = " zyxedcba " ; int k = 1 ; System . out . print ( largestString ( str , k ) + "NEW_LINE"); } }