LeetCode 题解工作台
K 个元素的最大和
给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。你需要执行以下操作 恰好 k 次,最大化你的得分: 从 nums 中选择一个元素 m 。 将选中的元素 m 从数组中删除。 将新元素 m + 1 添加到数组中。 你的得分增加 m 。 请你返回执行以上操作恰好 k 次后的最大得分。 示例…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 贪心·invariant
答案摘要
我们注意到,要使得最终的得分最大,我们应该尽可能地使得每次选择的元素最大。因此,我们第一次选择数组中的最大元素 ,第二次选择 ,第三次选择 ,以此类推,直到第 次选择 。这样的选择方式可以保证每次选择的元素都是当前数组中的最大值,因此最终的得分也是最大的。答案即为 个 的和加上 ,即 $k \times x + (k - 1) \times k / 2$。 时间复杂度 ,其中 是数组的长度…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。你需要执行以下操作 恰好 k 次,最大化你的得分:
- 从
nums中选择一个元素m。 - 将选中的元素
m从数组中删除。 - 将新元素
m + 1添加到数组中。 - 你的得分增加
m。
请你返回执行以上操作恰好 k 次后的最大得分。
示例 1:
输入:nums = [1,2,3,4,5], k = 3 输出:18 解释:我们需要从 nums 中恰好选择 3 个元素并最大化得分。 第一次选择 5 。和为 5 ,nums = [1,2,3,4,6] 。 第二次选择 6 。和为 6 ,nums = [1,2,3,4,7] 。 第三次选择 7 。和为 5 + 6 + 7 = 18 ,nums = [1,2,3,4,8] 。 所以我们返回 18 。 18 是可以得到的最大答案。
示例 2:
输入:nums = [5,5,5], k = 2 输出:11 解释:我们需要从 nums 中恰好选择 2 个元素并最大化得分。 第一次选择 5 。和为 5 ,nums = [5,5,6] 。 第二次选择 6 。和为 6 ,nums = [5,5,7] 。 所以我们返回 11 。 11 是可以得到的最大答案。
提示:
1 <= nums.length <= 1001 <= nums[i] <= 1001 <= k <= 100
解题思路
方法一:贪心 + 数学
我们注意到,要使得最终的得分最大,我们应该尽可能地使得每次选择的元素最大。因此,我们第一次选择数组中的最大元素 ,第二次选择 ,第三次选择 ,以此类推,直到第 次选择 。这样的选择方式可以保证每次选择的元素都是当前数组中的最大值,因此最终的得分也是最大的。答案即为 个 的和加上 ,即 。
时间复杂度 ,其中 是数组的长度。空间复杂度 。
class Solution:
def maximizeSum(self, nums: List[int], k: int) -> int:
x = max(nums)
return k * x + k * (k - 1) // 2
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate efficiently handles greedy algorithms and invariant tracking.
- question_mark
Candidate considers performance and time complexity when choosing data structures.
- question_mark
Candidate demonstrates the ability to optimize code using sorting or priority queues.
常见陷阱
外企场景- error
Failing to properly update the array after each operation, leading to incorrect choices.
- error
Using inefficient data structures, causing the solution to exceed time limits.
- error
Not validating the greedy approach thoroughly for all edge cases, especially when k is large.
进阶变体
外企场景- arrow_right_alt
Modify the problem to allow for selecting smaller elements and track the resulting score.
- arrow_right_alt
Consider the problem where the number of operations k is variable and depends on the input.
- arrow_right_alt
Solve the problem by using dynamic programming instead of a greedy approach.