Skip to content

3620. Maximum Number Of Distinct Elements After Operations

Array Greedy Sorting

Problem - Maximum Number Of Distinct Elements After Operations

Medium

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:

Input: nums = [1,2,2,3,3,4], k = 2

Output: 6

Explanation:

nums changes to [-1, 0, 1, 2, 3, 4] after performing operations on the first four elements.

Example 2:

Input: nums = [4,4,4,4], k = 1

Output: 3

Explanation:

By adding -1 to nums[0] and 1 to nums[1], nums changes to [3, 5, 4, 4].

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 0 <= k <= 109

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def maxDistinctElements(self, nums: List[int], k: int) -> int:
        nums.sort()
        result = 0
        last = float('-inf')

        for num in nums:
            current = min(num + k, max(num - k, last + 1))
            if current > last:
                result += 1
                last = current

        return result

Submission Stats:

  • Runtime: 796 ms (27.22%)
  • Memory: 31.7 MB (54.44%)