LeetCode 题解工作台
和有限的最长子序列
给你一个长度为 n 的整数数组 nums ,和一个长度为 m 的整数数组 queries 。 返回一个长度为 m 的数组 answer ,其中 answer[i] 是 nums 中 元素之和小于等于 queries[i] 的 子序列 的 最大 长度 。 子序列 是由一个数组删除某些元素(也可以不删除…
5
题型
8
代码语言
3
相关题
当前训练重点
简单 · 二分·搜索·答案·空间
答案摘要
根据题目描述,对于每个 ,我们需要找到一个子序列,使得该子序列的元素和不超过 ,且该子序列的长度最大化。显然,我们应该选择尽可能小的元素,这样才能使得子序列的长度最大化。 因此,我们可以先将数组 进行升序排序,然后对于每个 ,我们可以使用二分查找,找到最小的下标 ,使得 $\textit{nums}[0] + \textit{nums}[1] + \cdots + \textit{nums}[j…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个长度为 n 的整数数组 nums ,和一个长度为 m 的整数数组 queries 。
返回一个长度为 m 的数组 answer ,其中 answer[i] 是 nums 中 元素之和小于等于 queries[i] 的 子序列 的 最大 长度 。
子序列 是由一个数组删除某些元素(也可以不删除)但不改变剩余元素顺序得到的一个数组。
示例 1:
输入:nums = [4,5,2,1], queries = [3,10,21] 输出:[2,3,4] 解释:queries 对应的 answer 如下: - 子序列 [2,1] 的和小于或等于 3 。可以证明满足题目要求的子序列的最大长度是 2 ,所以 answer[0] = 2 。 - 子序列 [4,5,1] 的和小于或等于 10 。可以证明满足题目要求的子序列的最大长度是 3 ,所以 answer[1] = 3 。 - 子序列 [4,5,2,1] 的和小于或等于 21 。可以证明满足题目要求的子序列的最大长度是 4 ,所以 answer[2] = 4 。
示例 2:
输入:nums = [2,3,4,5], queries = [1] 输出:[0] 解释:空子序列是唯一一个满足元素和小于或等于 1 的子序列,所以 answer[0] = 0 。
提示:
n == nums.lengthm == queries.length1 <= n, m <= 10001 <= nums[i], queries[i] <= 106
解题思路
方法一:排序 + 前缀和 + 二分查找
根据题目描述,对于每个 ,我们需要找到一个子序列,使得该子序列的元素和不超过 ,且该子序列的长度最大化。显然,我们应该选择尽可能小的元素,这样才能使得子序列的长度最大化。
因此,我们可以先将数组 进行升序排序,然后对于每个 ,我们可以使用二分查找,找到最小的下标 ,使得 。此时 就是满足条件的子序列的元素和,且该子序列的长度为 。因此,我们可以将 加入答案数组中。
时间复杂度 ,空间复杂度 或 。其中 和 分别是数组 和 的长度。
class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
nums.sort()
s = list(accumulate(nums))
return [bisect_right(s, q) for q in queries]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate should demonstrate an understanding of binary search applied to a sorted array.
- question_mark
Look for the ability to break down the problem into subproblems like sorting and binary searching over a prefix sum.
- question_mark
The candidate should highlight solving each query independently to optimize the approach.
常见陷阱
外企场景- error
Overlooking the importance of sorting the array before attempting to answer queries efficiently.
- error
Incorrectly implementing binary search, leading to incorrect subsequences being selected for each query.
- error
Neglecting the need to compute prefix sums, which is essential for optimizing the solution.
进阶变体
外企场景- arrow_right_alt
Adjust the problem to find subsequences with a sum strictly less than the query value.
- arrow_right_alt
Allow for multiple queries to be processed simultaneously using a more advanced algorithm like a segment tree.
- arrow_right_alt
Modify the problem to return the sum of the largest subsequence instead of its size.