Skip to content

Commit 0a6830a

Browse files
Add sliding_window_maximum function
Implement sliding window maximum algorithm using deque.
1 parent e2a78d4 commit 0a6830a

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
from collections import deque
2+
from typing import List
3+
4+
5+
def sliding_window_maximum(nums: List[int], k: int) -> List[int]:
6+
"""
7+
Return a list of the maximum values in each sliding window of size k.
8+
9+
This algorithm runs in O(n) time using a deque to keep track of useful elements.
10+
11+
Parameters
12+
----------
13+
nums : List[int]
14+
The input list of integers.
15+
k : int
16+
The window size.
17+
18+
Returns
19+
-------
20+
List[int]
21+
A list containing the maximum of each sliding window.
22+
23+
Examples
24+
--------
25+
>>> sliding_window_maximum([1,3,-1,-3,5,3,6,7], 3)
26+
[3, 3, 5, 5, 6, 7]
27+
>>> sliding_window_maximum([9, 11], 2)
28+
[11]
29+
>>> sliding_window_maximum([4, -2], 1)
30+
[4, -2]
31+
>>> sliding_window_maximum([], 3)
32+
[]
33+
>>> sliding_window_maximum([1,2,3], 0)
34+
[]
35+
"""
36+
if not nums or k <= 0:
37+
return []
38+
39+
dq: deque[int] = deque()
40+
result: List[int] = []
41+
42+
for i, num in enumerate(nums):
43+
# Remove indices that are out of the current window
44+
while dq and dq[0] <= i - k:
45+
dq.popleft()
46+
47+
# Remove smaller values as they are not useful
48+
while dq and nums[dq[-1]] < num:
49+
dq.pop()
50+
51+
dq.append(i)
52+
53+
# Add the current max to the result once the window is of size k
54+
if i >= k - 1:
55+
result.append(nums[dq[0]])
56+
57+
return result

0 commit comments

Comments
 (0)