> For the complete documentation index, see [llms.txt](https://hzhang.gitbook.io/leetcode-record/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hzhang.gitbook.io/leetcode-record/treemap/1438.-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md).

# 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

```java
class Solution {
    public int longestSubarray(int[] nums, int limit) {
        TreeMap<Integer, Set<Integer>> map = new TreeMap<>();
        int i = 0;
        int maxLen = 0;
        for (int j = 0; j < nums.length; j++) {
            Set<Integer> set = map.get(nums[j]);
            if (set == null) {
                set = new HashSet<>();
            }
            set.add(j);
            map.put(nums[j], set);
            int minVal = map.firstKey();
            int maxVal = map.lastKey();
            while (maxVal - minVal > limit) {
                set = map.get(nums[i]);
                set.remove(i);
                if (set.isEmpty()) {
                    map.remove(nums[i]);
                }
                i++;
                minVal = map.firstKey();
                maxVal = map.lastKey();
            }
            maxLen = Math.max(maxLen, j-i+1);
        }
        return maxLen;
    }
}
```
