Minimize the Maximum Adjacent Element Difference - Problem

You are given an array of integers nums. Some values in nums are missing and are denoted by -1.

You must choose a pair of positive integers (x, y) exactly once and replace each missing element with either x or y.

You need to minimize the maximum absolute difference between adjacent elements of nums after replacements.

Return the minimum possible difference.

Input & Output

Example 1 — Basic Case with Two Missing
$ Input: nums = [1,-1,3,-1]
Output: 1
💡 Note: Replace first -1 with 2 and second -1 with 2: [1,2,3,2]. Adjacent differences: |2-1|=1, |3-2|=1, |2-3|=1. Maximum difference is 1.
Example 2 — All Missing Elements
$ Input: nums = [-1,-1,-1]
Output: 0
💡 Note: Replace all with same value: [1,1,1]. All adjacent differences are 0, so maximum difference is 0.
Example 3 — No Missing Elements
$ Input: nums = [1,2,3]
Output: 1
💡 Note: No replacements needed. Adjacent differences: |2-1|=1, |3-2|=1. Maximum difference is 1.

Constraints

  • 2 ≤ nums.length ≤ 105
  • nums[i] == -1 or 1 ≤ nums[i] ≤ 109
  • At least one element is -1

Visualization

Tap to expand
INPUT1-13-1Missing elements marked in redNeed to choose (x,y) to replace -1sGoal: minimize max adjacent differenceALGORITHM1. Binary Search RangeSearch answer in [0, 2×10⁹]2. Feasibility CheckCan we achieve max_diff = mid?3. Constraint AnalysisCalculate valid ranges for each -14. Validate (x,y)Check if two values satisfy allRESULT1232Replaced with x=2, y=2Differences: [1,1,1]Answer: 1Key Insight:Binary search on the answer space combined with constraint propagation allows us toefficiently find the minimum achievable maximum difference without trying all combinations.TutorialsPoint - Minimize Maximum Adjacent Difference | Binary Search on Answer
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
23.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen