Suppose we have an array nums and another value k, we have to find the most competitive subsequence of nums of size k. Here a subsequence s1 is more competitive than a subsequence s2 (of equal size) if in the first position where s1 and s2 differ, subsequence s1 has a number less than the corresponding number in s2.
So, if the input is like nums = [4,6,3,7] k = 2, then the output will be [3,7] because among all subsequences of size 2, {[4,6], [4,3], [4,7], [6,3], [6,7], [3,7]}, the [3,7] is the most competitive.
To solve this, we will follow these steps −
- attempts := size of nums - k
- stack := a new list
- for each num in nums, do
- while stack is not empty and num < top of stack and attempts > 0, do
- pop element from stack
- attempts := attempts - 1
- push num into stack
- while stack is not empty and num < top of stack and attempts > 0, do
- return top k elements of stack
Example
Let us see the following implementation to get better understanding −
def solve(nums, k): attempts = len(nums) - k stack = [] for num in nums: while stack and num < stack[-1] and attempts > 0: stack.pop() attempts -= 1 stack.append(num) return stack[:k] nums = [4,6,3,7] k = 2 print(solve(nums, k))
Input
[4,6,3,7], 2
Output
[3,7]