Skip to content

Commit 024e90d

Browse files
Jiang15cclauss
andauthored
add monotonic queue algorithm (#10531)
* add monotonic queue algorithm * add monotonic queue algorithm * add monotonic queue algorithm * monotonic queue * updating DIRECTORY.md * Rename file to correct directory structure * updating DIRECTORY.md --------- Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: cclauss <cclauss@users.noreply.github.com>
1 parent b061ef6 commit 024e90d

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

‎DIRECTORY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,7 @@
370370
* [Circular Queue Linked List](data_structures/queues/circular_queue_linked_list.py)
371371
* [Double Ended Queue](data_structures/queues/double_ended_queue.py)
372372
* [Linked Queue](data_structures/queues/linked_queue.py)
373+
* [Monotonic Queue](data_structures/queues/monotonic_queue.py)
373374
* [Priority Queue Using List](data_structures/queues/priority_queue_using_list.py)
374375
* [Queue By List](data_structures/queues/queue_by_list.py)
375376
* [Queue By Two Stacks](data_structures/queues/queue_by_two_stacks.py)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from __future__ import annotations
2+
3+
from collections import deque
4+
5+
arr = [1, 3, -1, -3, 5, 3, 6, 7]
6+
window_size = 3
7+
expect = [3, 3, 5, 5, 6, 7]
8+
9+
10+
def max_sliding_window(arr: list[float], window_size: int) -> list[float]:
11+
"""
12+
Given an array of integers nums, there is a sliding window of size k which is moving
13+
from the very left of the array to the very right.
14+
Each time the sliding window of length window_size moves right by one position.
15+
Return the max sliding window.
16+
>>> max_sliding_window(arr, window_size) == expect
17+
True
18+
"""
19+
max_val = []
20+
mono_queue: deque = deque()
21+
for i in range(len(arr)):
22+
# pop the element if the index is outside the window size k
23+
if mono_queue and i - mono_queue[0] >= window_size:
24+
mono_queue.popleft()
25+
# keep the queue monotonically decreasing
26+
# so that the max value is always on the top
27+
while mono_queue and arr[i] >= arr[mono_queue[-1]]:
28+
mono_queue.pop()
29+
mono_queue.append(i)
30+
# the maximum value is the first element in queue
31+
if i >= window_size - 1:
32+
max_val.append(arr[mono_queue[0]])
33+
return max_val
34+
35+
36+
if __name__ == "__main__":
37+
from doctest import testmod
38+
39+
testmod()

0 commit comments

Comments
 (0)