fork(1) download
  1. from collections import deque
  2.  
  3. def diff_sliding_window(arr, win):
  4.  
  5. if win > len(arr):
  6. return []
  7.  
  8. win_maxes = [] # max of each window
  9.  
  10. #Q contains indexes of items in the window that are greater than
  11. #all items to the right of them. This always includes the last item
  12. #in the window
  13. Q = deque()
  14.  
  15. #fill Q for initial window
  16. for i in range(win):
  17. #remove anything that isn't greater than the new item
  18. while len(Q) > 0 and arr[i] >= arr[Q[-1]]:
  19. Q.pop()
  20. Q.append(i)
  21. win_maxes.append(arr[Q[0]])
  22.  
  23. for i in range(win, len(arr)):
  24. #remove indexes (at most 1, really) left of window
  25. while len(Q) > 0 and Q[0] <= (i-win):
  26. Q.popleft()
  27.  
  28. #remove anything that isn't greater than the new item
  29. while len(Q) > 0 and arr[i] >= arr[Q[-1]]:
  30. Q.pop()
  31. Q.append(i)
  32. win_maxes.append(arr[Q[0]])
  33.  
  34. return win_maxes
  35.  
  36. print(diff_sliding_window([12, 1, 78, 90, 57, 89, 56],3))
  37. print(diff_sliding_window([1, 3, -1, -3, 5, 3, 6, 7],3))
  38.  
Success #stdin #stdout 0s 9136KB
stdin
Standard input is empty
stdout
[78, 90, 90, 90, 89]
[3, 3, 5, 5, 6, 7]