- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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))

[4,6,3,7], 2

[3,7]

- Related Questions & Answers
- Program to find closest subsequence sum in Python
- Find the longest subsequence of an array having LCM at most K in Python
- Program to Find the longest subsequence where the absolute difference between every adjacent element is at most k in Python.
- Program to Find Out the Largest K-Divisible Subsequence Sum in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest fibonacci subsequence in Python
- Program to find frequency of the most frequent element in Python
- Program to find out the length of longest palindromic subsequence using Python
- Python program to find the most occurring character and its count
- Program to find length of longest circular increasing subsequence in python
- Program to find lexicographically smallest subsequence of size k in Python
- C# program to find the most frequent element

Advertisements