#3397

Maximum Number of Distinct Elements After Operations

Medium
ArrayGreedySortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Sort the array and adjust each element to maximize distinct values by filling gaps with the allowed range.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array to handle duplicates easily.
  2. 2Step 2: Use a set to track distinct elements and iterate through the sorted array.
  3. 3Step 3: For each element, calculate the nearest available distinct value within the range and add it to the set.
solution.py8 lines
1def maxDistinct(nums, k):
2    nums = sorted(set(nums))
3    distinct = set()
4    for num in nums:
5        while num in distinct:
6            num += 1
7        distinct.add(num)
8    return len(distinct)

Complexity note: Sorting the array takes O(n log n), and using a set for distinct elements takes O(n).

  • 1Sorting helps manage duplicates effectively.
  • 2Using a set ensures uniqueness while adjusting values.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.