Skip to content

3397. Maximum Number of Distinct Elements After Operations 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int maxDistinctElements(vector<int>& nums, int k) {
    int ans = 0;
    int occupied = INT_MIN;

    ranges::sort(nums);

    for (const int num : nums)
      if (occupied < num + k) {
        occupied = max(occupied + 1, num - k);
        ++ans;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int maxDistinctElements(int[] nums, int k) {
    int ans = 0;
    int occupied = Integer.MIN_VALUE;

    Arrays.sort(nums);

    for (final int num : nums)
      if (occupied < num + k) {
        occupied = Math.max(occupied + 1, num - k);
        ++ans;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def maxDistinctElements(self, nums: list[int], k: int) -> int:
    ans = 0
    occupied = -math.inf

    for num in sorted(nums):
      if occupied < num + k:
        occupied = max(occupied + 1, num - k)
        ans += 1

    return ans