class Solution:
def longestSubarray(self, A: List[int], limit: int) -> int:
# main idea: convert diff of any two elements within array <= limit ==> diff between min and max elments of subarray
# time O(N) space O(N)
maxd = collections.deque() # monotonically decreasing order by index
mind = collections.deque() # monotonically increasing order by index
l = 0
res = 1
n = len(A)
for r in range(n):
while len(maxd) and A[r] > maxd[-1]: maxd.pop()
while len(mind) and A[r] < mind[-1]: mind.pop()
maxd.append(A[r])
mind.append(A[r])
# shrink left ptr if diff exceed limit
while maxd[0] - mind[0] > limit: # left ptr move forward ,but it may affect maxd and mind since elements on left of l will be discarded.
if maxd[0] == A[l]:maxd.popleft() # maxd[0] is the max number in maxd
if mind[0] == A[l]:mind.popleft() # maxd[0] is the smallest number in mind
l += 1
res = max(res,r-l+1)
return res