You are given an array of integers nums. Some values in nums are missing and are denoted…
- User
You are given an array of integers nums. Some values in nums are missing and are denoted by -1.
You can 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.
Example 1:
Input: nums = [1,2,-1,10,8]
Output: 4
Explanation:
By choosing the pair as (6, 7), nums can be changed to [1, 2, 6, 10, 8].
The absolute differences between adjacent elements are:
|1 - 2| == 1 |2 - 6| == 4 |6 - 10| == 4 |10 - 8| == 2 Example 2:
Input: nums = [-1,-1,-1]
Output: 0
Explanation:
By choosing the pair as (4, 4), nums can be changed to [4, 4, 4].
Example 3:
Input: nums = [-1,10,-1,8]
Output: 1
Explanation:
By choosing the pair as (11, 9), nums can be changed to [11, 10, 9, 8].
Constraints:
2 <= nums.length <= 105 nums[i] is either -1 or in the range [1, 109].
def minDifference(self, nums): n = len(nums) best = 0 adj = set() for i in range(n): if nums[i] != -1: if i > 0 and nums[i - 1] != -1: best = max(best, abs(nums[i] - nums[i - 1])) if nums[i] == -1: if i > 0 and nums[i - 1] != -1: adj.add(nums[i - 1]) if i < n - 1 and nums[i + 1] != -1: adj.add(nums[i + 1]) if not adj: return best
codeadj = sorted(adj) def check(mid): m = len(adj) x_end = adj[0] + mid i = 0 while i < m and adj[i] <= x_end: i += 1 if i == m: return True y_start = adj[i] - mid if y_start > x_end + mid: return False y_end = y_start + mid j = i while j < m and adj[j] <= y_end: j += 1 return j == m l, r = 0, adj[-1] - adj[0] while l < r: m = (l + r) // 2 if check(m): r = m else: l = m + 1 return max(best, l) . Wrong Answer678 / 951 testcases passed Input nums = [1,2,-1,10,8] Use Testcase Output 3 Expected 4
- Assistant