---
# System prepended metadata

title: 2817. Minimum Absolute Difference Between Elements With Constraint
tags: [Leetcode, TreeMap, Binary Search, Medium]

---

Link: https://leetcode.com/problems/minimum-absolute-difference-between-elements-with-constraint/
## 思路
TreeSet/Binary Search
find valid nearest integer of each element
## Code
```java=
class Solution {
    public int minAbsoluteDifference(List<Integer> nums, int x) {
        TreeSet<Integer> set = new TreeSet<>();
        int ans = Integer.MAX_VALUE;
        for(int i=x; i<nums.size(); i++){
            set.add(nums.get(i-x));
            int curr = nums.get(i);
            Integer ceil = set.ceiling(nums.get(i));
            Integer floor = set.floor(nums.get(i));
            if(ceil!=null) ans = Math.min(ans, ceil-curr);
            if(floor!=null) ans = Math.min(ans, curr-floor);
        }
        return ans;
    }
}
```