1
1
"""
2
- A Monotonic Queue is a data structure that supports efficient insertion, deletion,
2
+ A Monotonic Queue is a data structure that supports efficient insertion, deletion,
3
3
and retrieval of elements in a specific order, typically in increasing or decreasing order.
4
4
"""
5
5
6
6
from collections import deque
7
7
8
+
8
9
class MonotonicQueue :
9
10
def __init__ (self ):
10
11
self .deque = deque ()
@@ -21,14 +22,15 @@ def pop(self, value):
21
22
if self .deque and self .deque [0 ] == value :
22
23
self .deque .popleft ()
23
24
25
+
24
26
def sliding_window_max (nums , k ):
25
27
if not nums or k == 0 :
26
28
return []
27
29
if k >= len (nums ):
28
30
return [max (nums )]
29
31
if k == 1 :
30
32
return nums
31
-
33
+
32
34
q = MonotonicQueue ()
33
35
result = []
34
36
for i in range (len (nums )):
@@ -40,9 +42,10 @@ def sliding_window_max(nums, k):
40
42
q .pop (nums [i - k + 1 ])
41
43
return result
42
44
45
+
43
46
# Test cases
44
- print (sliding_window_max ([], 3 )) # Edge case: Empty list
45
- print (sliding_window_max ([1 , 2 ], 3 )) # Edge case: k > len(nums)
46
- print (sliding_window_max ([1 , 3 , 2 , 5 , 4 ], 1 )) # Edge case: k == 1
47
- print (sliding_window_max ([1 , 3 , 2 , 5 , 4 ], 5 )) # Edge case: k == len(nums)
47
+ print (sliding_window_max ([], 3 )) # Edge case: Empty list
48
+ print (sliding_window_max ([1 , 2 ], 3 )) # Edge case: k > len(nums)
49
+ print (sliding_window_max ([1 , 3 , 2 , 5 , 4 ], 1 )) # Edge case: k == 1
50
+ print (sliding_window_max ([1 , 3 , 2 , 5 , 4 ], 5 )) # Edge case: k == len(nums)
48
51
print (sliding_window_max ([8 , 5 , 10 , 7 , 9 , 4 , 15 , 12 , 90 , 13 ], 3 )) # Normal case
0 commit comments