LeetCode 题解工作台
执行操作后不同元素的最大数量
给你一个整数数组 nums 和一个整数 k 。 你可以对数组中的每个元素 最多 执行 一次 以下操作: 将一个在范围 [-k, k] 内的整数加到该元素上。 返回执行这些操作后, nums 中可能拥有的不同元素的 最大 数量。 示例 1: 输入: nums = [1,2,2,3,3,4], k = …
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们不妨对数组 排序,然后从左到右考虑每个元素 。 对于第一个元素,我们可以贪心地将其变为 $x - k$,这样可以使得 尽可能小,给后续的元素留下更多的空间。我们用变量 当前使用到的元素的最大值,初始化为负无穷大。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个整数数组 nums 和一个整数 k。
你可以对数组中的每个元素 最多 执行 一次 以下操作:
- 将一个在范围
[-k, k]内的整数加到该元素上。
返回执行这些操作后,nums 中可能拥有的不同元素的 最大 数量。
示例 1:
输入: nums = [1,2,2,3,3,4], k = 2
输出: 6
解释:
对前四个元素执行操作,nums 变为 [-1, 0, 1, 2, 3, 4],可以获得 6 个不同的元素。
示例 2:
输入: nums = [4,4,4,4], k = 1
输出: 3
解释:
对 nums[0] 加 -1,以及对 nums[1] 加 1,nums 变为 [3, 5, 4, 4],可以获得 3 个不同的元素。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 1090 <= k <= 109
解题思路
方法一:贪心 + 排序
我们不妨对数组 排序,然后从左到右考虑每个元素 。
对于第一个元素,我们可以贪心地将其变为 ,这样可以使得 尽可能小,给后续的元素留下更多的空间。我们用变量 当前使用到的元素的最大值,初始化为负无穷大。
对于后续的元素 ,我们可以贪心地将其变为 。这里的 表示我们尽可能地将 变得更小,但不能小于 ,如果存在该值,且小于 ,我们就可以将 变为该值,不重复元素数加一,然后我们更新 为该值。
遍历结束,我们就得到了不重复元素的最大数量。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def maxDistinctElements(self, nums: List[int], k: int) -> int:
nums.sort()
ans = 0
pre = -inf
for x in nums:
cur = min(x + k, max(x - k, pre + 1))
if cur > pre:
ans += 1
pre = cur
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Understanding of greedy algorithms
- question_mark
Ability to optimize operations on duplicates
- question_mark
Familiarity with sorting and its impact on optimization
常见陷阱
外企场景- error
Incorrect application of the operation (add or subtract 1) to non-duplicate elements
- error
Failing to prioritize duplicates when applying operations
- error
Overlooking the need to track distinct elements during modification
进阶变体
外企场景- arrow_right_alt
Allowing more than one operation per element
- arrow_right_alt
Considering a larger k value or different operations
- arrow_right_alt
Limiting the number of elements that can be modified