Maximum Number of Distinct Elements After Operations

You are given an integer array nums and an integer k.

You are allowed to perform the following operation on each element of the array at most once:

  • Add an integer in the range [-k, k] to the element.

Return the maximum possible number of distinct elements in nums after performing the operations.

Example 1
Inputnums = [1,2,2,3,3,4], k = 2
Output6
nums changes to [-1, 0, 1, 2, 3, 4] after performing operations on the first four elements, giving 6 distinct elements.
Example 2
Inputnums = [4,4,4,4], k = 1
Output3
By adding -1 to nums[0] and 1 to nums[1], nums changes to [3, 5, 4, 4], giving 3 distinct elements.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
  • 0 <= k <= 10^9

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate