1673. Find the Most Competitive Subsequence

T: O(n)
S: O(k)
```java
class Solution {
    public int[] mostCompetitive(int[] nums, int k) {
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < nums.length; i++) {
            // nums.length - i (right pushed)
            while (!stack.isEmpty() && nums[i] < stack.peek() && nums.length - i + stack.size() - 1 >= k) {
                stack.pop();
            }
            if (stack.size() < k) { // we only want k elements
                stack.push(nums[i]);
            }
        }
        int[] result = new int[k];
        for (int i = k - 1; i >= 0; i--) {
            result[i] = stack.pop();
        }
        return result;
    }
}
/*
T: O(n)
S: O(k)

from questions
[1,3,4] is more competitive than [1,3,5]
actually we always remain small one in following numbers

 0 1 2 3 4 5 6 7
[2,4,3,3,5,4,9,6], k = 4
         x -> total 8 - curr idx 4 = 4 (we still has 4 can add(include yourself))
        
        so if we can quarantee, stack.size() - 1 (after pop) && right element(include yourself) 
        still fulfill requirement >= k

        we can pop

        if (stack.size() < k) { // we only want k elements, so we can push
*/
```

Last updated