Space
Open
From Fieldwork
Scales
Archive
We use the Sliding Window technique combined with two Monotonic Deques (queues). One deque maintains the maximums in the current window, and the other maintains the minimums.
class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
max_d = deque() # Monotonically decreasing (front is max)
min_d = deque() # Monotonically increasing (front is min)
left = 0
res = 0
for right, num in enumerate(nums):
# 1. Maintain max_d: remove elements smaller than current num
while max_d and max_d[-1] < num:
max_d.pop()
max_d.append(num)
# 2. Maintain min_d: remove elements larger than current num
while min_d and min_d[-1] > num:
min_d.pop()
min_d.append(num)
# 3. Check condition: if diff > limit, shrink window from left
while max_d[0] - min_d[0] > limit:
# If the number leaving the window was the max or min,
# pop it from the respective deque
if max_d[0] == nums[left]:
max_d.popleft()
if min_d[0] == nums[left]:
min_d.popleft()
left += 1
# 4. Update max length
res = max(res, right - left + 1)
return resPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode