LeetCode 1673 Find the Most Competitive Subsequence (Python)

Posted by 小明MaxMing on January 21, 2021

题目

Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.

An array’s subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.

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.

解题思路

贪心,维护一个单调栈使得结果中的数是最小的,当剩余数的个数刚好能凑够k个的时候,就不能再pop了

代码

class Solution:
    def mostCompetitive(self, nums: List[int], k: int) -> List[int]:
        stack = []
        for i, n in enumerate(nums):
            while stack and stack[-1] > n and i + k - len(stack) < len(nums):
                stack.pop()
            if len(stack) < k:
                stack.append(n)
        return stack

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅