-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathsliding_window_max.py
More file actions
45 lines (35 loc) · 1.06 KB
/
sliding_window_max.py
File metadata and controls
45 lines (35 loc) · 1.06 KB
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
36
37
38
39
40
41
42
43
44
45
"""
Sliding Window Maximum (Heap-based)
Given an array and a window size k, find the maximum element in each
sliding window using a deque that maintains decreasing order of values.
Reference: https://leetcode.com/problems/sliding-window-maximum/
Complexity:
Time: O(n)
Space: O(k)
"""
from __future__ import annotations
import collections
def max_sliding_window(nums: list[int], k: int) -> list[int]:
"""Find the maximum in each sliding window of size k.
Args:
nums: Input array of integers.
k: Window size.
Returns:
List of maximum values for each window position.
Examples:
>>> max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3)
[3, 3, 5, 5, 6, 7]
"""
if not nums:
return nums
queue: collections.deque[int] = collections.deque()
result: list[int] = []
for num in nums:
if len(queue) < k:
queue.append(num)
else:
result.append(max(queue))
queue.popleft()
queue.append(num)
result.append(max(queue))
return result