Data Structures & AlgorithmsVery hard

Why does the lexicographically largest subsequence after deleting k digits come from a greedy stack?

  1. A. The greedy always removes the largest digit.
  2. B. A smaller digit followed by a larger digit should be removed first, because keeping the earlier digit larger improves the string most.
  3. C. Sorting the digits in descending order is always the answer.
  4. D. Removing digits from the end is always optimal.

Correct answer: B. A smaller digit followed by a larger digit should be removed first, because keeping the earlier digit larger improves the string most.

The leftmost position dominates the string's order, so putting a larger digit earlier is the priority. A stack removes a smaller predecessor whenever a larger digit arrives, using the budget where it helps most.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic