#2817

Minimum Absolute Difference Between Elements With Constraint

expert · 1045 · lc medium +32 · failed · 37.3% accepted · 768 likes · top 15%

Description

A 0-indexed integer array nums and an integer x are given.

Among all pairs of indices (i, j) satisfying abs(i - j) >= x, find the pair that minimizes abs(nums[i] - nums[j]).

Return that minimum absolute difference.

Example 1:

Input: nums = [4,3,2,4], x = 2
Output: 0
Explanation: We can select nums[0] = 4 and nums[3] = 4.
They are at least 2 indices apart, and their absolute difference is the minimum, 0.
It can be shown that 0 is the optimal answer.

Example 2:

Input: nums = [5,3,2,10,15], x = 1
Output: 1
Explanation: We can select nums[1] = 3 and nums[2] = 2.
They are at least 1 index apart, and their absolute difference is the minimum, 1.
It can be shown that 1 is the optimal answer.

Example 3:

Input: nums = [1,2,3,4], x = 3
Output: 3
Explanation: We can select nums[0] = 1 and nums[3] = 4.
They are at least 3 indices apart, and their absolute difference is the minimum, 3.
It can be shown that 3 is the optimal answer.

Code

1
2
3