class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
n = len(nums)
res = 1
for i in range(n):
mini = maxi = nums[i]
for j in range(i + 1, n):
mini = min(mini, nums[j])
maxi = max(maxi, nums[j])
if maxi - mini > limit:
break
res = max(res, j - i + 1)
return resclass Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
maxHeap = []
minHeap = []
j = 0
res = 0
for i, v in enumerate(nums):
heapq.heappush(maxHeap, (-v, i))
heapq.heappush(minHeap, (v, i))
while -maxHeap[0][0] - minHeap[0][0] > limit:
j += 1
while maxHeap and maxHeap[0][1] < j:
heapq.heappop(maxHeap)
while minHeap and minHeap[0][1] < j:
heapq.heappop(minHeap)
res = max(res, i - j + 1)
return resclass Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
tree = SortedDict()
l = res = 0
for r, x in enumerate(nums):
tree[x] = tree.get(x, 0) + 1
while tree.peekitem(-1)[0] - tree.peekitem(0)[0] > limit:
y = nums[l]
tree[y] -= 1
if tree[y] == 0:
del tree[y]
l += 1
res = max(res, r - l + 1)
return resclass Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
min_q = deque() # mono increasing
max_q = deque() # mono decreasing
l = res = 0
for r in range(len(nums)):
while min_q and nums[r] < min_q[-1]:
min_q.pop()
while max_q and nums[r] > max_q[-1]:
max_q.pop()
min_q.append(nums[r])
max_q.append(nums[r])
while max_q[0] - min_q[0] > limit:
if nums[l] == max_q[0]:
max_q.popleft()
if nums[l] == min_q[0]:
min_q.popleft()
l += 1
res = max(res, r - l + 1)
return resclass Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
inc = deque([nums[0]])
dec = deque([nums[0]])
res = 1
j = 0
for i in range(1, len(nums)):
while inc and inc[-1] > nums[i]:
inc.pop()
while dec and dec[-1] < nums[i]:
dec.pop()
inc.append(nums[i])
dec.append(nums[i])
if dec[0] - inc[0] > limit:
if dec[0] == nums[j]:
dec.popleft()
if inc[0] == nums[j]:
inc.popleft()
j += 1
return len(nums) - j