Skip to content

Commit 2ac3757

Browse files
Refactor sliding_window_maximum function signature
Updated type hints and parameter names for clarity.
1 parent 0a6830a commit 2ac3757

File tree

1 file changed

+17
-15
lines changed

1 file changed

+17
-15
lines changed
Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,49 @@
11
from collections import deque
2-
from typing import List
32

43

5-
def sliding_window_maximum(nums: List[int], k: int) -> List[int]:
4+
def sliding_window_maximum(nums: list[int], window_size: int) -> list[int]:
65
"""
7-
Return a list of the maximum values in each sliding window of size k.
8-
6+
Return a list of the maximum values in each sliding window of the given size.
97
This algorithm runs in O(n) time using a deque to keep track of useful elements.
108
119
Parameters
1210
----------
13-
nums : List[int]
11+
nums : list[int]
1412
The input list of integers.
15-
k : int
16-
The window size.
13+
window_size : int
14+
The size of the sliding window.
1715
1816
Returns
1917
-------
20-
List[int]
18+
list[int]
2119
A list containing the maximum of each sliding window.
2220
2321
Examples
2422
--------
25-
>>> sliding_window_maximum([1,3,-1,-3,5,3,6,7], 3)
23+
>>> sliding_window_maximum([1, 3, -1, -3, 5, 3, 6, 7], 3)
2624
[3, 3, 5, 5, 6, 7]
2725
>>> sliding_window_maximum([9, 11], 2)
2826
[11]
2927
>>> sliding_window_maximum([4, -2], 1)
3028
[4, -2]
3129
>>> sliding_window_maximum([], 3)
3230
[]
33-
>>> sliding_window_maximum([1,2,3], 0)
31+
>>> sliding_window_maximum([1, 2, 3], 0)
3432
[]
33+
34+
Reference
35+
---------
36+
https://en.wikipedia.org/wiki/Sliding_window_protocol
3537
"""
36-
if not nums or k <= 0:
38+
if not nums or window_size <= 0:
3739
return []
3840

3941
dq: deque[int] = deque()
40-
result: List[int] = []
42+
result: list[int] = []
4143

4244
for i, num in enumerate(nums):
4345
# Remove indices that are out of the current window
44-
while dq and dq[0] <= i - k:
46+
while dq and dq[0] <= i - window_size:
4547
dq.popleft()
4648

4749
# Remove smaller values as they are not useful
@@ -50,8 +52,8 @@ def sliding_window_maximum(nums: List[int], k: int) -> List[int]:
5052

5153
dq.append(i)
5254

53-
# Add the current max to the result once the window is of size k
54-
if i >= k - 1:
55+
# Add the current max to the result once the window is of size window_size
56+
if i >= window_size - 1:
5557
result.append(nums[dq[0]])
5658

5759
return result

0 commit comments

Comments
 (0)