Skip to content
LC-3397 Medium LeetCode

3397. Maximum Number of Distinct Elements After Operations

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 31% Topics: Array, Greedy, Sorting
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(nlogn)
# Space: O(1)

# sort, greedy
class Solution(object):
    def maxDistinctElements(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        result = 0
        nums.sort()
        curr = float("-inf")
        for x in nums:
            if curr > x+k:
                continue
            curr = max(curr, x-k)+1
            result += 1
        return result

Solution from kamyu104/LeetCode-Solutions · MIT