Minimize the Maximum Adjacent Element Difference - Problem

You're given an array of integers nums where some values are missing and represented by -1. Your task is to strategically replace each missing element with one of two positive integers x or y that you choose.

The goal is to minimize the maximum absolute difference between any two adjacent elements in the final array. You must choose exactly one pair (x, y) and use only these two values for all replacements.

Example: Given [1, -1, -1, 4], you might choose x=2, y=3 and create [1, 2, 3, 4] with max adjacent difference of 1.

Return the minimum possible maximum adjacent difference after optimal replacements.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1, -1, -1, 4]
โ€บ Output: 1
๐Ÿ’ก Note: We can choose x=2, y=3 and create [1,2,3,4]. Adjacent differences are |2-1|=1, |3-2|=1, |4-3|=1. Maximum is 1.
example_2.py โ€” All Missing
$ Input: [-1, -1, -1]
โ€บ Output: 0
๐Ÿ’ก Note: We can choose x=1, y=1 and create [1,1,1]. All adjacent differences are 0, so maximum is 0.
example_3.py โ€” No Missing
$ Input: [1, 3, 5]
โ€บ Output: 2
๐Ÿ’ก Note: No missing elements, so we just calculate maximum adjacent difference: max(|3-1|, |5-3|) = max(2, 2) = 2.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 109 when nums[i] โ‰  -1
  • At least one element is -1
  • You must use exactly two distinct positive integers for replacements
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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