Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.
 
Example 1:
Input: nums = [8,2,4,7], limit = 4
Output: 2 
Explanation: All subarrays are: 
[8] with maximum absolute diff |8-8| = 0 <= 4.
[8,2] with maximum absolute diff |8-2| = 6 > 4. 
[8,2,4] with maximum absolute diff |8-2| = 6 > 4.
[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.
[2] with maximum absolute diff |2-2| = 0 <= 4.
[2,4] with maximum absolute diff |2-4| = 2 <= 4.
[2,4,7] with maximum absolute diff |2-7| = 5 > 4.
[4] with maximum absolute diff |4-4| = 0 <= 4.
[4,7] with maximum absolute diff |4-7| = 3 <= 4.
[7] with maximum absolute diff |7-7| = 0 <= 4. 
Therefore, the size of the longest subarray is 2.

Example 2:
Input: nums = [10,1,2,4,7,2], limit = 5
Output: 4 
Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.

Example 3:
Input: nums = [4,2,2,2,4,4,2,2], limit = 0
Output: 3

 
Constraints:

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
0 <= limit <= 10^9

```python

USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
    import resource as _res
except Exception:
    _res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
    from typing import *
except Exception:
    pass
try:
    sys.setrecursionlimit(1_000_000)
except Exception:
    pass
try:
    import site as _site
    try:
        _sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
        for _p in _sys_sites:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
    try:
        _usp = _site.getusersitepackages()
        if isinstance(_usp, str):
            _usp = [_usp]
        for _p in _usp:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
except Exception:
    pass

def _disabled_input(*args, **kwargs):
    raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input

ns = {"__name__": "__judge__"}  # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
    if not _k.startswith("_"):
        ns[_k] = _v
_CODE = "from sortedcontainers import SortedList\nclass Solution:\n    def longestSubarray(self, nums: List[int], limit: int) -> int:\n        # we keep two pointers and we keep track of min and max between those pointers\n        # if the new number being added is having difference from both min and max within the range we increase j and update min and max if necessary else we increase i till we get the difference less than target while changing i and also we keep on updating the min and max\n        # it can mark the beginning of a new sub array\n        # however if we can make this update faster constant time and at max we need to increase i from i to j by deleting each number then also it is in worse case O(nk) instead of linear we can save sometime\n        # we do not need indices and so we can use SortedList instead of SortedDict to make processing of finding min and max after changing i faster\n        minheap = [[nums[0],0]]\n        maxheap = [[-nums[0],0]]\n        left = -1\n        res = 1\n        for i,val in enumerate(nums[1:]):\n            j = i+1\n            while len(maxheap) and len(minheap) and max(val,-maxheap[0][0]) - min(val,minheap[0][0]) > limit:\n                if val == max(val,-maxheap[0][0]):\n                    v,l = heapq.heappop(minheap)\n                if minheap and val == min(val,minheap[0][0]):\n                    v,l = heapq.heappop(maxheap)\n                left = max(l,left)\n            res = max(j-left,res)\n            heapq.heappush(minheap,[val,j])\n            heapq.heappush(maxheap,[-val,j])\n        return res\n        \n        '''\n        s = SortedList()\n        # we keep on adding new values to the sortedList and when we get max - min greater than target then we keep on removing values from the list till the sorted list becomes valid again\n        # thus we have a solution with O(nlogn) complexity and faster than the one with sortedDict although it is having same complexity\n        max_length = 0\n        j = 0\n        for i in range(len(nums)):\n            s.add(nums[i])\n            while s and s[-1] - s[0] > limit:\n                s.remove(nums[j])\n                j += 1\n            max_length = max(max_length,i-j + 1)\n        return max_length\n        '''\n        # for the following approach also the time limit gets exceeded because although operations on dictionary are O(logn) we are doing them for more number of times then expected\n        '''\n        # i.e. if min is our problem then we need to increase i till we find new min \n        # i.e we need to start from i = i + max_index of current_min\n        # and if max is our problem then we need to increase i till we find new max\n        # i.e we need to start from i = i + max_index of current_max\n        # and if both are a problem then we need to increase i till max when both are changed\n        # this we can do if we use a hashmap mapping each value from i to j with its max index in the array we do not care for intermediate indices\n        max_length = -float('inf')\n        mapping = SortedDict()\n        Min = nums[0]\n        Max = nums[0]\n        mapping[Min] = 0\n        i = 0\n        while i < len(nums):\n            j = i\n            # print('a',i,j,Max,Min)\n            while j < len(nums) and abs(nums[j] - Min) <= limit and abs(nums[j] - Max) <= limit:\n                Max = max(Max,nums[j])\n                Min = min(Min,nums[j])\n                # we are just concerned with the max value\n                mapping[nums[j]] = j\n                j += 1\n                max_length = max(max_length,j - i)\n                \n            # print('b',i,j,Min,Max)\n            if j >= len(nums)-1:\n                break\n            else:\n                mapping[nums[j]] = j\n                while i <= j and (abs(nums[j] - Min) > limit or abs(nums[j] - Max) > limit):\n                    if abs(nums[j] - Min) > limit and abs(nums[j] - Max) > limit:\n                        i = max(i,max(mapping[Min],mapping[Max]) + 1)\n                        del mapping[Max]\n                        if Min in mapping.keys():\n                            del mapping[Min]\n\n                    elif abs(nums[j] - Min) > limit:\n                        i = max(i,mapping[Min] + 1)\n                        del mapping[Min]\n                        \n                    elif abs(nums[j] - Max) > limit:\n                        i = max(i,mapping[Max] + 1)\n                        del mapping[Max]\n                    # after each update we need to update min and max and the following steps will take O(n)\n                    Min = mapping.peekitem(0)[0]\n                    Max = mapping.peekitem()[0]\n                    while mapping[Min] < i:\n                        del mapping[Min]\n                        Min = mapping.peekitem(0)[0]\n                    while mapping[Max] < i:\n                        del mapping[Max]\n                        Max = mapping.peekitem()[0]\n                    \n                # print(mapping)\n                # print('c',i,j,Max,Min)\n        return max_length\n        \n        '''\n        # for the following approach time limit gets exceeded\n        '''\n        max_length = -float('inf')\n        Min = nums[0]\n        Max = nums[0]\n        i = 0\n        while i < len(nums):\n            j = i \n            #print('a',i,j,Max,Min)\n            while j < len(nums) and abs(nums[j] - Min) <= limit and abs(nums[j] - Max) <= limit:\n                Max = max(Max,nums[j])\n                Min = min(Min,nums[j])\n                j += 1\n                max_length = max(max_length,j - i)\n            #print('b',i,j,Max,Min,len(nums))\n            if j >= len(nums)-1:\n                break\n            else:\n                while i < j and nums[i] != Min and nums[i] != Max:\n                    i += 1\n                while i < j and (abs(nums[j] - Min) > limit or abs(nums[j] - Max) > limit):\n                    i += 1\n                    #print(i)\n                    Min = min(nums[i:j+1])\n                    Max = max(nums[i:j+1])\n                    #print('c',i,j,Max,Min)\n        return max_length\n        '''            \n        \n        \n        \n"
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)

_target = None
_fn_name = 'longestSubarray'
if _fn_name:
    if "Solution" in ns:
        try:
            _obj = ns["Solution"]()
            if hasattr(_obj, _fn_name):
                _target = getattr(_obj, _fn_name)
        except Exception:
            _target = None
    if _target is None and _fn_name in ns and callable(ns[_fn_name]):
        _target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
    _cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
    _user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
    if len(_user_funcs) == 1:
        _target = _user_funcs[0]
if _target is None:
    raise RuntimeError(f"Could not resolve callable '{_fn_name}'")

_raw = sys.stdin.read().strip()
if _raw:
    _parsed = json.loads(_raw)
    if isinstance(_parsed, dict):
        _kwargs = _parsed.get("kwargs", {})
        _args = _parsed.get("args", [])
    else:
        _args, _kwargs = _parsed, {}
else:
    _args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
    _args = [_args]
_res = _target(*_args, **_kwargs)
try:
    sys.stdout.write(repr(_res) + "\n")
except Exception:
    pass

```

Measured memory_bytes: