We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 1b00da2 commit f5a819cCopy full SHA for f5a819c
alternative/hard/sliding_window_maximum.py
@@ -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]
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments