Maximize distinct values after unique ± offsets
Maximize Distinct Values After Unique ± Offsets
You are given an integer array a of length n and a non-negative integer k.
For each index i, you must choose:
- an integer offset
d_isuch that0 <= d_i <= k, and - a sign, either
+or-,
and replace a[i] with a[i] + d_i or a[i] - d_i.
Constraint: All chosen offsets must be distinct across indices (i.e., d_i != d_j for i != j).
Your goal is to maximize the number of distinct integers in the resulting array after all replacements.
Return that maximum possible number of distinct values.
Example
- Input:
a = [0, 0, 0],k = 1 - Output:
3 - Explanation: Choose offsets
0, 1(but offsets must be distinct, so for 3 elements we can used = 0, 1only ifk=1; instead, one valid construction is to allowdto be chosen per element distinctly within[0,k]—for this example, a maximal distinct outcome is[-1, 0, 1]by applying-1, 0, +1to the three zeros.
Notes / Clarifications
- Offsets are integers.
- Offset
0is allowed. - The sign choice is independent per element.
Constraints
1 <= n <= 2 * 10^50 <= k <= 10^9-10^9 <= a[i] <= 10^9
Implement a function that returns the maximum possible number of distinct values.
AI interview prep
Core dilemma
The fundamental contradiction between the explicit 'All chosen offsets must be distinct across indices (i.e., d_i != d_j for i != j)' constraint and the provided example's explanation, which implies d_i values can be repeated (e.g., using d=1 twice for k=1). This forces a critical clarification from the candidate or a well-reasoned assumption, especially considering `n` can be much larger than `k+1`.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Maximize distinct values after unique ± offsets
Maximize Distinct Values After Unique ± Offsets
You are given an integer array a of length n and a non-negative integer k.
For each index i, you must choose:
- an integer offset
d_isuch that0 <= d_i <= k, and - a sign, either
+or-,
and replace a[i] with a[i] + d_i or a[i] - d_i.
Constraint: All chosen offsets must be distinct across indices (i.e., d_i != d_j for i != j).
Your goal is to maximize the number of distinct integers in the resulting array after all replacements.
Return that maximum possible number of distinct values.
Example
- Input:
a = [0, 0, 0],k = 1 - Output:
3 - Explanation: Choose offsets
0, 1(but offsets must be distinct, so for 3 elements we can used = 0, 1only ifk=1; instead, one valid construction is to allowdto be chosen per element distinctly within[0,k]—for this example, a maximal distinct outcome is[-1, 0, 1]by applying-1, 0, +1to the three zeros.
Notes / Clarifications
- Offsets are integers.
- Offset
0is allowed. - The sign choice is independent per element.
Constraints
1 <= n <= 2 * 10^50 <= k <= 10^9-10^9 <= a[i] <= 10^9
Implement a function that returns the maximum possible number of distinct values.