My first instinct was to just iterate over every possible value in each element's window and greedily assign, which is O(N*K) and they were not impressed.
First, clarify that shifting each element independently within [-k, k] means each original value can be replaced by any integer in its interval [a_i - k, a_i + k]. The goal is to choose one integer from each interval to maximize the number of distinct chosen values. This is a classic interval scheduling problem: sort intervals by right endpoint and greedily assign the smallest available integer that is >= left endpoint and not already used.
Pro tip: Mention that the greedy choice is optimal because choosing the smallest possible value preserves larger values for later intervals, and this can be proven by an exchange argument. Also, note that the answer is at most n, and the greedy runs in O(n log n) time.
Explain that each element a_i can be changed to any integer in [a_i - k, a_i + k], and we want to maximize the number of distinct integers in the final array.
Treat each element as an interval [L_i, R_i] where L_i = a_i - k and R_i = a_i + k. We need to pick one integer from each interval to maximize distinct picks.
Sort the intervals by R_i ascending. This ordering ensures that when we process an interval, we can assign the smallest available integer that is >= L_i and not used before.
Maintain a set of used integers. For each interval in sorted order, find the smallest integer >= L_i that is not in the set and <= R_i. If found, add it to the set and increment the count.
The size of the set (or the count of successful assignments) is the maximum number of distinct values achievable.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.