LeetCode 题解工作台
找到和最大的长度为 K 的子序列
给你一个整数数组 nums 和一个整数 k 。你需要找到 nums 中长度为 k 的 子序列 ,且这个子序列的 和最大 。 请你返回 任意 一个长度为 k 的整数子序列。 子序列 定义为从一个数组里删除一些元素后,不改变剩下元素的顺序得到的数组。 示例 1: 输入: nums = [2,1,3,3]…
4
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们先创建一个索引数组 ,数组中的每个元素是数组 的下标。然后我们根据数组 的值对索引数组 进行排序,排序的规则是 $\textit{nums}[i] < \textit{nums}[j]$,其中 和 是索引数组 中的两个下标。 排序完成后,我们取索引数组 的最后 个元素,这 个元素对应的就是数组 中最大的 个元素。然后我们对这 个下标进行排序,得到的就是最大的 个元素在…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums 和一个整数 k 。你需要找到 nums 中长度为 k 的 子序列 ,且这个子序列的 和最大 。
请你返回 任意 一个长度为 k 的整数子序列。
子序列 定义为从一个数组里删除一些元素后,不改变剩下元素的顺序得到的数组。
示例 1:
输入:nums = [2,1,3,3], k = 2 输出:[3,3] 解释: 子序列有最大和:3 + 3 = 6 。
示例 2:
输入:nums = [-1,-2,3,4], k = 3 输出:[-1,3,4] 解释: 子序列有最大和:-1 + 3 + 4 = 6 。
示例 3:
输入:nums = [3,4,3,3], k = 2 输出:[3,4] 解释: 子序列有最大和:3 + 4 = 7 。 另一个可行的子序列为 [4, 3] 。
提示:
1 <= nums.length <= 1000-105 <= nums[i] <= 1051 <= k <= nums.length
解题思路
方法一:排序
我们先创建一个索引数组 ,数组中的每个元素是数组 的下标。然后我们根据数组 的值对索引数组 进行排序,排序的规则是 ,其中 和 是索引数组 中的两个下标。
排序完成后,我们取索引数组 的最后 个元素,这 个元素对应的就是数组 中最大的 个元素。然后我们对这 个下标进行排序,得到的就是最大的 个元素在数组 中的顺序。
时间复杂度 ,空间复杂度 。其中 为数组的长度。
class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
idx = sorted(range(len(nums)), key=lambda i: nums[i])[-k:]
return [nums[i] for i in sorted(idx)]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \log n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
They ask what the greedy choice is before discussing implementation, which points to selecting the k largest values first.
- question_mark
They emphasize subsequence instead of subset, which is a signal that original index order must be restored after selection.
- question_mark
They bring up duplicate numbers like [3,4,3,3], which usually means a hash map of counts is safer than a set.
常见陷阱
外企场景- error
Sorting the whole array and returning the first k values directly breaks the subsequence requirement because it loses original order.
- error
Using a set for chosen numbers fails when the optimal answer needs repeated values, such as taking both 3s in [2,1,3,3].
- error
Picking the first k large-looking numbers during one scan can miss a later better value, so greedy must be based on the global top k values, not local choices.
进阶变体
外企场景- arrow_right_alt
Use a min-heap of size k instead of sorting all values to keep only the current top k elements, then rebuild order with counts.
- arrow_right_alt
Store selected indices by sorting pairs of value and index, choosing the best k pairs, and sorting those indices before output.
- arrow_right_alt
If asked for the maximum sum only, the subsequence-order rebuild disappears and the task becomes just tracking the top k values.