1673. Find the Most Competitive Subsequence
package LeetCode_1673 import java.util.* /** * 1673. Find the Most Competitive Subsequence * https://leetcode.com/problems/find-the-most-competitive-subsequence/ * 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. Example 1: Input: nums = [3,5,2,6], k = 2 Output: [2,6] Explanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive. * */ class Solution { /* * solution: Stack,scan each number, check current num if large than then the first one in stack, * pop the large one, keep the increasing stack; * Time:O(n), Space:O(n) * */ fun mostCompetitive(nums: IntArray, k: Int): IntArray { var needRemoveCount = nums.size - k val stack = Stack<Int>() for (i in nums.indices) { while (stack.isNotEmpty() && nums[i] < stack.peek() && needRemoveCount > 0) { stack.pop() needRemoveCount-- } stack.push(nums[i]) } //handle case some case, for example 1111 while (needRemoveCount > 0) { stack.pop() needRemoveCount-- } val result = IntArray(k) var index = k - 1 //replace element from right to left,so no need to reverse while (stack.isNotEmpty()) { result[index--] = stack.pop() } return result } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)