LeetCode 题解工作台

执行操作后不同元素的最大数量

给你一个整数数组 nums 和一个整数 k 。 你可以对数组中的每个元素 最多 执行 一次 以下操作: 将一个在范围 [-k, k] 内的整数加到该元素上。 返回执行这些操作后, nums 中可能拥有的不同元素的 最大 数量。 示例 1: 输入: nums = [1,2,2,3,3,4], k = …

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们不妨对数组 排序,然后从左到右考虑每个元素 。 对于第一个元素,我们可以贪心地将其变为 $x - k$,这样可以使得 尽可能小,给后续的元素留下更多的空间。我们用变量 当前使用到的元素的最大值,初始化为负无穷大。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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 <= 105
  • 1 <= nums[i] <= 109
  • 0 <= k <= 109
lightbulb

解题思路

方法一:贪心 + 排序

我们不妨对数组 nums\textit{nums} 排序,然后从左到右考虑每个元素 xx

对于第一个元素,我们可以贪心地将其变为 xkx - k,这样可以使得 xx 尽可能小,给后续的元素留下更多的空间。我们用变量 pre\textit{pre} 当前使用到的元素的最大值,初始化为负无穷大。

对于后续的元素 xx,我们可以贪心地将其变为 min(x+k,max(xk,pre+1))\min(x + k, \max(x - k, \textit{pre} + 1))。这里的 max(xk,pre+1)\max(x - k, \textit{pre} + 1) 表示我们尽可能地将 xx 变得更小,但不能小于 pre+1\textit{pre} + 1,如果存在该值,且小于 x+kx + k,我们就可以将 xx 变为该值,不重复元素数加一,然后我们更新 pre\textit{pre} 为该值。

遍历结束,我们就得到了不重复元素的最大数量。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 为数组 nums\textit{nums} 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Understanding of greedy algorithms

  • question_mark

    Ability to optimize operations on duplicates

  • question_mark

    Familiarity with sorting and its impact on optimization

warning

常见陷阱

外企场景
  • 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

swap_horiz

进阶变体

外企场景
  • 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

help

常见问题

外企场景

执行操作后不同元素的最大数量题解:贪心·invariant | LeetCode #3397 中等