forked from ngiengkianyew/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_018.py
More file actions
35 lines (23 loc) · 701 Bytes
/
problem_018.py
File metadata and controls
35 lines (23 loc) · 701 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from collections import deque
def get_sliding_max(a, k):
window_max_elements = list()
if not a:
return None
if len(a) <= k:
return max(a)
dq = deque()
for i in range(k):
while dq and a[dq[-1]] < a[i]:
dq.pop()
dq.append(i)
window_max_elements.append(a[dq[0]])
for i in range(k, len(a)):
while dq and dq[0] <= i - k:
dq.popleft()
while dq and a[dq[-1]] < a[i]:
dq.pop()
dq.append(i)
window_max_elements.append(a[dq[0]])
return window_max_elements
assert get_sliding_max([10, 5, 2, 7, 8, 7], 3) == [10, 7, 8, 8]
assert get_sliding_max([5, 2, 1], 2) == [5, 2]