Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f5a819c

Browse files
committed
feat: finish sliding window maximum in python
1 parent 1b00da2 commit f5a819c

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from collections import deque
2+
3+
def max_sliding_window(nums, k):
4+
result = []
5+
window = deque()
6+
7+
for i in range(len(nums)):
8+
# Remove the first element if it is out of the window
9+
if window and window[0] <= i - k:
10+
window.popleft()
11+
12+
# Remove all elements smaller than the current one
13+
while window and nums[window[-1]] <= nums[i]:
14+
window.pop()
15+
16+
# Add the current element
17+
window.append(i)
18+
19+
# Add the maximum to the result
20+
if i >= k - 1:
21+
result.append(nums[window[0]])
22+
23+
return result
24+
25+
# Test cases
26+
assert max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
27+
assert max_sliding_window([1], 1) == [1]
28+
assert max_sliding_window([1, -1], 1) == [1, -1]
29+
assert max_sliding_window([9, 11], 2) == [11]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /