class Solution:
def continuousSubarrays(self, nums: List[int]) -> int:
# indices of max elements in decreasing order in valid window
maxq = deque()
# indices of min elements in increasing order in valid window
minq = deque()
# start of window
i = 0
# result count
res = 0
for j, n in enumerate(nums):
# maxq maintenance
while maxq and nums[maxq[len(maxq) - 1]] < n:
maxq.pop()
maxq.append(j)
# minq maintenance
while minq and nums[minq[len(minq) - 1]] > n:
minq.pop()
minq.append(j)
# make sure window is valid wrt min - max element criteria
while maxq and minq and abs(nums[maxq[0]] - nums[minq[0]]) > 2:
# one of maxq[0] or minq[0] needs to be taken out
# then condition needs to be checked again
# find the one that occurs earlier
# take that out since it will keep the other
# if you take out the one that occurs later,
# it basically means removing both
if maxq[0] < minq[0]:
i = maxq.popleft() + 1
else:
i = minq.popleft() + 1
# now window is valid wrt min - max criteria
# i and j are the boundary indices
res += j - i + 1
return res