class Solution {
public int longestSubarray(int[] nums, int limit) {
TreeMap<Integer, Deque<Integer>> map = new TreeMap<>();
int ans = 0;
int i = 0;
int j = 0;
while (j < nums.length) {
Deque<Integer> indexes = map.get(nums[j]);
if (indexes == null) {
indexes = new ArrayDeque<>();
}
if (indexes.isEmpty() || indexes.peekLast() != j) {
indexes.offerLast(j);
map.put(nums[j], indexes);
}
int max = map.lastKey();
int min = map.firstKey();
if (max - min > limit) {
Deque<Integer> iIndexes = map.get(nums[i]);
iIndexes.pollFirst();
if (iIndexes.size() == 0) {
map.remove(nums[i]);
} else {
map.put(nums[i], iIndexes);
}
i++;
} else {
ans = Math.max(ans, j - i + 1);
j++;
}
}
return ans;
}
}