Problem Description
You are given an integer array nums and an integer k. Each element in nums can be adjusted at most once by adding any integer between -k and k (inclusive) to it. The goal is to choose adjustments to maximize the number of distinct elements in the resulting array.
Key Insights
- Each element x in nums has a range [x - k, x + k] to which it can be adjusted.
- The problem can be transformed into an interval assignment task where for each element you must pick one integer from its allowed interval.
- A greedy strategy is effective: sort the intervals by their ending value and assign the smallest possible integer that is greater than the number assigned previously.
- The greedy approach is similar to interval scheduling, ensuring that we leave room to assign distinct values for subsequent intervals.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the intervals. Space Complexity: O(n) for storing interval ranges (or O(1) additional space if done in-place).
Solution
We first convert each element nums[i] into an interval [nums[i] - k, nums[i] + k]. Once we have these intervals, we sort them by the end (right boundary). Then, we iterate over each interval and greedily choose the smallest number that is larger than the last assigned number while still lying within the current interval. If such a number exists, we assign it and update our last assigned number; otherwise, we skip that interval. This process ensures that we maximize the number of distinct assignments.
The main data structures used are:
- An array of intervals.
- A variable to track the last assigned distinct value.
The algorithmic approach is greedy, with the key trick being the sort by interval ending, which guarantees that when we assign a value for the current interval, we leave as much room as possible for future intervals.