Maximize equal values via one subarray shift
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates a candidate's understanding of array manipulation, frequency analysis, range-update reasoning, and optimization under a single contiguous subarray operation.
Constraints
- 1 <= n <= 10^4 (n may also be 0; return [0, 0, -1, 0] for an empty array).
- -10^9 <= A[i] <= 10^9.
- delta may be any integer (negative, zero, or positive).
- Indices are 0-based and inclusive: 0 <= l <= r < n.
- If multiple (l, r, delta) achieve the maximum frequency, returning any one is acceptable; the max frequency itself is unique.
Examples
Input: [2, 4, 6, 2, 4, 7]
Expected Output: [3, 1, 1, -2]
Explanation: Shift A[1..1]=[4] by -2 -> [2,2,6,2,4,7], three 2s. Max frequency 3.
Input: [5]
Expected Output: [1, 0, 0, 0]
Explanation: Single element already has frequency 1; no-op is optimal.
Hints
- Fix a target value V you want to appear most often. Outside the shifted window, every V already present still counts; inside the window, you can only turn one source value W into V by choosing delta = V - W (so all W's inside become V, and any V's inside are lost).
- For a fixed (V, W) pair, the net change to the count of V over a window equals (#W in window) - (#V in window). Assign score +1 to positions equal to W, -1 to positions equal to V, 0 otherwise, then take the maximum-sum contiguous subarray (Kadane) to pick the best window.
- The final answer for a pair is totalCount(V) + bestKadaneSum. Iterate over all ordered distinct pairs (V, W), keep the no-op baseline (max raw frequency), and track the (l, r, delta = V - W) that produced the best window.