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
Understanding the Visualization
1
Input
Array nums and adjustment range k
2
Process
Sort array and greedily assign smallest available values
3
Output
Maximum possible distinct elements
Key Takeaway
🎯 Key Insight: Sort first, then greedily assign the smallest unused value within each element's valid range
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code