Find the Most Competitive Subsequence¶

We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5.¶

The idea of the algorithm is to iterate over the number and use a stack containing the most competitive subsequence so far:¶
1) Iterate over the nums¶
2) While a) the stack is not empty, b) the current num is smaller than the stack top value and c) we have pass possibilites (if we pass to much values we won't be able to obtain a sequence of k values): pop the top value¶
3) Once the current num is at is right place (values on his left are smaller) just append it to the stack¶
4) Return the k first values of the stack¶
In [ ]:
def mostCompetitive(self, nums: List[int], k: int) -> List[int]:
    # if we need k element of the list we can't pass more than len(nums) - k times
    pass_possibilities = len(nums) - k
    stack = []

    for num in nums:
        # while there is element in stack and the current num is smaller than the top and we still have pass possibilites just pop
        while stack and (num < stack[-1]) and (pass_possibilities > 0):
            stack.pop()
            pass_possibilities -= 1
        stack.append(num)

    return(stack[:k])