1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
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;
}
}
Last updated