fork download
  1. from collections import deque
  2. def main(arr,k):
  3. ans=0
  4. min_q=deque()
  5. max_q=deque()
  6. i=0
  7. n=len(arr)
  8. for j in range(n):
  9. val=arr[j]
  10. while max_q and arr[max_q[-1]]<=val:
  11. max_q.pop()
  12. max_q.append(j)
  13.  
  14. while min_q and arr[min_q[-1]]>=val:
  15. min_q.pop()
  16. min_q.append(j)
  17.  
  18. while abs(arr[max_q[0]]-arr[min_q[0]])>k:
  19. if i==max_q[0]:
  20. max_q.popleft()
  21. if i==min_q[0]:
  22. min_q.popleft()
  23. i+=1
  24.  
  25. ans=max(ans,j-i+1)
  26. return ans
  27.  
  28. print(main([5, 2, 2, 6, 4, 7, 5, 8],3))
Success #stdin #stdout 0.09s 8008KB
stdin
Standard input is empty
stdout
4