Problem Description
Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k. A subsequence is derived from the array by deleting some (or no) elements without changing the order. One subsequence is considered more competitive than another if at the first differing position, it has a smaller number.
Key Insights
- Use a greedy algorithm with a monotonic stack to continuously build the smallest lexicographical sequence.
- Ensure that after potential removals, there are still enough elements remaining to complete a subsequence of size k.
- At each step, compare the current number with the last element in the stack and decide whether to pop from the stack.
Space and Time Complexity
Time Complexity: O(n), where n is the length of nums. Space Complexity: O(k), since the stack holds at most k elements.
Solution
The solution iterates over the array while maintaining a monotonic stack. For each element, if the current element is smaller than the last element in the stack and there are enough elements left to reach a total of k, the algorithm pops from the stack to remove suboptimal choices. This greedy process guarantees that the resulting subsequence is the most competitive (i.e., lexicographically smallest possible). Once the iteration is finished, the stack contains the desired subsequence.