class Solution:
def longestSubarray(self, A: List[int], limit: int) -> int:
d = []
ans = 1
for i, a in enumerate(A):
bisect.insort(d, a)
if len(d) > 1:
while d[-1] - d[0] > limit:
d.remove(A[i - len(d)+1])
ans = max(ans, len(d))
return ans
from sortedcontainers import SortedList
class Solution:
def longestSubarray(self, A: List[int], limit: int) -> int:
d = SortedList()
ans = 1
for i, a in enumerate(A):
d.add(a)
if len(d) > 1:
while d[-1] - d[0] > limit:
d.remove(A[i - len(d)+1])
ans = max(ans, len(d))
return ans
class Solution:
def longestSubarray(self, A: List[int], limit: int) -> int:
q1, q2 = collections.deque(), collections.deque()
ans = 1
i = 0
for j, a in enumerate(A):
while q1 and q1[-1] < a:
q1.pop()
q1.append(a)
while q2 and q2[-1] > a:
q2.pop()
q2.append(a)
while i < j and q1 and q2 and q1[0] - q2[0] > limit:
if A[i] == q1[0]: q1.popleft()
elif A[i] == q2[0]: q2.popleft()
i += 1
ans = max(ans, j - i + 1)
return ans