Untitled
unknown
plain_text
10 months ago
1.3 kB
6
Indexable
import java.util.TreeSet;
public class Solution {
public int minAbsoluteDifference(int[] nums, int x) {
TreeSet<Integer> rightWindowSet = new TreeSet<>();
int minDiff = Integer.MAX_VALUE;
// Traverse the array from right to left, starting from nums.length - x - 1
for (int i = nums.length - x - 1; i >= 0; i--) {
rightWindowSet.add(nums[i + x]);
Integer ceil = rightWindowSet.ceiling(nums[i]);
if (lower != null) {
minDiff = Math.min(minDiff, Math.abs(nums[i] - ceil));
}
Integer floor = rightWindowSet.floor(nums[i]);
if (higher != null) {
minDiff = Math.min(minDiff, Math.abs(nums[i] - floor));
}
}
return minDiff;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test cases
System.out.println(solution.minAbsoluteDifference(new int[]{4, 3, 2, 4}, 2)); // Output: 0
System.out.println(solution.minAbsoluteDifference(new int[]{5, 3, 2, 10, 15}, 1)); // Output: 1
System.out.println(solution.minAbsoluteDifference(new int[]{1, 2, 3, 4}, 3)); // Output: 3
}
}
Editor is loading...
Leave a Comment