text: Lexicographically largest possible String after removal of K characters | C ++ 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; string largestString ( string num , int k ) { string ans = " " ; for ( auto i : num ) { while ( ans . length ( ) && ans . back ( ) < i && k > 0 ) { ans . pop_back ( ) ; k -- ; } ans . push_back ( i ) ; } while ( ans . length ( ) and k -- ) { ans . pop_back ( ) ; } return ans ; } int main ( ) { string str = " zyxedcba " ; int k = 1 ; cout << largestString ( str , k ) << endl ; }