Lexicographically largest possible String after removal of K characters | Python3 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
def largestString ( num , k ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in range ( len ( num ) ) : NEW_LINE INDENT while ( len ( ans ) and ans [ - 1 ] < num [ i ] and k > 0 ) : NEW_LINE INDENT ans . pop ( ) NEW_LINE k -= 1 NEW_LINE DEDENT ans . append ( num [ i ] ) NEW_LINE DEDENT while ( len ( ans ) and k ) : NEW_LINE INDENT k -= 1 NEW_LINE ans . pop ( ) NEW_LINE DEDENT return ans NEW_LINE DEDENT str = " zyxedcba " NEW_LINE k = 1 NEW_LINE print ( * largestString ( str , k ) , sep = " " ) NEW_LINE