LeetCode 题解工作台
最大子序列的分数
给你两个下标从 0 开始的整数数组 nums1 和 nums2 ,两者长度都是 n ,再给你一个正整数 k 。你必须从 nums1 中选一个长度为 k 的 子序列 对应的下标。 对于选择的下标 i 0 , i 1 ,..., i k - 1 ,你的 分数 定义如下: nums1 中下标对应元素求和,…
4
题型
4
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
将 `nums2` 与 `nums1` 按照 `nums2` 降序排序,然后从前往后遍历,维护一个小根堆,堆中存储 `nums1` 中的元素,堆中元素个数不超过 个,同时维护一个变量 ,表示堆中元素的和,遍历过程中不断更新答案。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 为数组 `nums1` 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你两个下标从 0 开始的整数数组 nums1 和 nums2 ,两者长度都是 n ,再给你一个正整数 k 。你必须从 nums1 中选一个长度为 k 的 子序列 对应的下标。
对于选择的下标 i0 ,i1 ,..., ik - 1 ,你的 分数 定义如下:
nums1中下标对应元素求和,乘以nums2中下标对应元素的 最小值 。- 用公式表示:
(nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] , nums2[i1], ... ,nums2[ik - 1])。
请你返回 最大 可能的分数。
一个数组的 子序列 下标是集合 {0, 1, ..., n-1} 中删除若干元素得到的剩余集合,也可以不删除任何元素。
示例 1:
输入:nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3 输出:12 解释: 四个可能的子序列分数为: - 选择下标 0 ,1 和 2 ,得到分数 (1+3+3) * min(2,1,3) = 7 。 - 选择下标 0 ,1 和 3 ,得到分数 (1+3+2) * min(2,1,4) = 6 。 - 选择下标 0 ,2 和 3 ,得到分数 (1+3+2) * min(2,3,4) = 12 。 - 选择下标 1 ,2 和 3 ,得到分数 (3+3+2) * min(1,3,4) = 8 。 所以最大分数为 12 。
示例 2:
输入:nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1 输出:30 解释: 选择下标 2 最优:nums1[2] * nums2[2] = 3 * 10 = 30 是最大可能分数。
提示:
n == nums1.length == nums2.length1 <= n <= 1050 <= nums1[i], nums2[j] <= 1051 <= k <= n
解题思路
方法一:排序 + 优先队列(小根堆)
将 nums2 与 nums1 按照 nums2 降序排序,然后从前往后遍历,维护一个小根堆,堆中存储 nums1 中的元素,堆中元素个数不超过 个,同时维护一个变量 ,表示堆中元素的和,遍历过程中不断更新答案。
时间复杂度 ,空间复杂度 。其中 为数组 nums1 的长度。
class Solution:
def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
nums = sorted(zip(nums2, nums1), reverse=True)
q = []
ans = s = 0
for a, b in nums:
s += b
heappush(q, b)
if len(q) == k:
ans = max(ans, s * a)
s -= heappop(q)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate understands greedy algorithms and the importance of sorting in optimization problems.
- question_mark
Ability to implement a heap and manage subsequence selection efficiently.
- question_mark
Shows familiarity with complexity trade-offs between sorting and heap-based solutions.
常见陷阱
外企场景- error
Not sorting nums2 properly, leading to a suboptimal selection of indices.
- error
Incorrectly handling edge cases where k = 1 or k = n, which can change the dynamics of the subsequence.
- error
Failing to utilize the min-heap effectively, leading to inefficient or incorrect subsequence score calculations.
进阶变体
外企场景- arrow_right_alt
Consider variations where nums1 and nums2 have different ranges of values.
- arrow_right_alt
Explore approaches where k is dynamically adjusted based on certain conditions.
- arrow_right_alt
Change the problem to use different operations, such as summing the elements instead of multiplying.