LeetCode 题解工作台
执行 K 次操作后的最大分数
给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。你的 起始分数 为 0 。 在一步 操作 中: 选出一个满足 0 的下标 i , 将你的 分数 增加 nums[i] ,并且 将 nums[i] 替换为 ceil(nums[i] / 3) 。 返回在 恰好 执行 k 次操作后,你可能获…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
要使得分数最大化,我们需要在每一步操作中,选择元素值最大的元素进行操作。因此,我们可以使用优先队列(大根堆)来维护当前元素值最大的元素。 每次从优先队列中取出元素值最大的元素 ,将答案加上 ,并将 替换为 $\lceil \frac{v}{3} \rceil$,加入优先队列。重复 次后,将答案返回即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。你的 起始分数 为 0 。
在一步 操作 中:
- 选出一个满足
0 <= i < nums.length的下标i, - 将你的 分数 增加
nums[i],并且 - 将
nums[i]替换为ceil(nums[i] / 3)。
返回在 恰好 执行 k 次操作后,你可能获得的最大分数。
向上取整函数 ceil(val) 的结果是大于或等于 val 的最小整数。
示例 1:
输入:nums = [10,10,10,10,10], k = 5 输出:50 解释:对数组中每个元素执行一次操作。最后分数是 10 + 10 + 10 + 10 + 10 = 50 。
示例 2:
输入:nums = [1,10,3,3,3], k = 3 输出:17 解释:可以执行下述操作: 第 1 步操作:选中 i = 1 ,nums 变为 [1,4,3,3,3] 。分数增加 10 。 第 2 步操作:选中 i = 1 ,nums 变为 [1,2,3,3,3] 。分数增加 4 。 第 3 步操作:选中 i = 2 ,nums 变为 [1,2,1,3,3] 。分数增加 3 。 最后分数是 10 + 4 + 3 = 17 。
提示:
1 <= nums.length, k <= 1051 <= nums[i] <= 109
解题思路
方法一:优先队列(大根堆)
要使得分数最大化,我们需要在每一步操作中,选择元素值最大的元素进行操作。因此,我们可以使用优先队列(大根堆)来维护当前元素值最大的元素。
每次从优先队列中取出元素值最大的元素 ,将答案加上 ,并将 替换为 ,加入优先队列。重复 次后,将答案返回即可。
时间复杂度 ,空间复杂度 或 。其中 为数组 的长度。
class Solution:
def maxKelements(self, nums: List[int], k: int) -> int:
h = [-v for v in nums]
heapify(h)
ans = 0
for _ in range(k):
v = -heappop(h)
ans += v
heappush(h, -(ceil(v / 3)))
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(k log n + n log n) due to heap operations and initial heap construction. Space complexity is O(n) for storing the heap elements. |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Ask about choosing a data structure to efficiently retrieve the largest element repeatedly.
- question_mark
Discuss the greedy invariant: always selecting the current maximum ensures optimal score.
- question_mark
Probe how ceil division affects subsequent operations and heap updates.
常见陷阱
外企场景- error
Forgetting to push the updated value back into the heap after each operation.
- error
Incorrectly computing ceil division which can reduce the total score.
- error
Not handling large k efficiently, leading to timeouts without heap optimization.
进阶变体
外企场景- arrow_right_alt
Modify the division factor from 3 to any integer greater than 1.
- arrow_right_alt
Use a min-heap to find the minimal score instead of maximal by adjusting the greedy choice.
- arrow_right_alt
Allow choosing multiple elements in one operation and summing them before applying ceil division.