Maximum Number of Distinct Elements After Operations - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,4], k = 2
Output: 3
💡 Note: We can adjust: 1→1, 2→3, 4→5, giving us [1,3,5] with 3 distinct elements. All adjustments are within [-2,2] range.
Example 2 — With Duplicates
$ Input: nums = [4,1,2,2], k = 2
Output: 4
💡 Note: After sorting [1,2,2,4], we can assign: 1→-1, 2→0, 2→1, 4→2, giving us [-1,0,1,2] with 4 distinct elements.
Example 3 — Small Range
$ Input: nums = [5,5,5], k = 1
Output: 3
💡 Note: We can adjust to [4,5,6] using adjustments [-1,0,+1], all within range [-1,1], giving 3 distinct elements.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ 109

Visualization

Tap to expand
Maximum Distinct Elements After Operations INPUT nums array: 1 idx 0 2 idx 1 4 idx 2 k = 2 Each element can be adjusted by [-2, +2] 1: [-1, 3] range 2: [0, 4] range 4: [2, 6] range nums = [1, 2, 4] k = 2 ALGORITHM STEPS 1 Sort Array [1,2,4] is already sorted 2 Process Greedily Pick smallest valid value 3 Avoid Duplicates Track last used value 4 Count Distinct Increment if valid choice Processing Steps: Element 1: choose -1 OK Element 2: choose 0 OK Element 4: choose 2 OK Result: [-1, 0, 2] all distinct! FINAL RESULT Modified Array: -1 0 2 All 3 values are distinct! Number Line: -1 0 2 4 OUTPUT 3 Maximum distinct elements Key Insight: By sorting first, we can greedily assign each element the smallest valid value that hasn't been used. This ensures maximum distinctness. For each element, try to pick max(prev+1, num-k) if within [num-k, num+k]. TutorialsPoint - Maximum Number of Distinct Elements After Operations | Greedy with Sorting
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen