[LeetCode] Minimum Absolute Difference Between Elements With Constraint

2817. Minimum Absolute Difference Between Elements With Constraint

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

Find the minimum absolute difference between two elements in the array that are at least x indices apart.

In other words, find two indices i and j such that abs(i - j) >= x and abs(nums[i] - nums[j]) is minimized.

Return an integer denoting the minimum absolute difference between two elements that are at least x indices apart.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int minAbsoluteDifference(vector<int>& nums, int x) {
map<long long, long long> ms;
for(int i = x; i < nums.size(); i++) ms[nums[i]] += 1;
long long res = INT_MAX;
for(int i = 0; ms.size(); i++) {
auto it = ms.lower_bound(nums[i]);
if(it != end(ms)) res = min(res, abs(nums[i] - it->first));
if(it != begin(ms)) res = min(res, abs(nums[i] - prev(it)->first));
if(--ms[nums[i+x]] == 0) ms.erase(nums[i+x]);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/13/PS/LeetCode/minimum-absolute-difference-between-elements-with-constraint/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.