Skip to content

Commit 9abc6f3

Browse files
committed
Sync LeetCode submission Runtime - 124 ms (99.00%), Memory - 30.9 MB (84.67%)
1 parent b23016b commit 9abc6f3

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<p>You are given an array of integers&nbsp;<code>nums</code>, there is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p>
2+
3+
<p>Return <em>the max sliding window</em>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3
10+
<strong>Output:</strong> [3,3,5,5,6,7]
11+
<strong>Explanation:</strong>
12+
Window position Max
13+
--------------- -----
14+
[1 3 -1] -3 5 3 6 7 <strong>3</strong>
15+
1 [3 -1 -3] 5 3 6 7 <strong>3</strong>
16+
1 3 [-1 -3 5] 3 6 7 <strong> 5</strong>
17+
1 3 -1 [-3 5 3] 6 7 <strong>5</strong>
18+
1 3 -1 -3 [5 3 6] 7 <strong>6</strong>
19+
1 3 -1 -3 5 [3 6 7] <strong>7</strong>
20+
</pre>
21+
22+
<p><strong class="example">Example 2:</strong></p>
23+
24+
<pre>
25+
<strong>Input:</strong> nums = [1], k = 1
26+
<strong>Output:</strong> [1]
27+
</pre>
28+
29+
<p>&nbsp;</p>
30+
<p><strong>Constraints:</strong></p>
31+
32+
<ul>
33+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
34+
<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
35+
<li><code>1 &lt;= k &lt;= nums.length</code></li>
36+
</ul>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Approach: Monotonic Deque
2+
3+
# Time: O(n)
4+
# Space: O(k)
5+
6+
from collections import deque
7+
8+
class Solution:
9+
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
10+
dq = deque()
11+
res = []
12+
13+
for i in range(k):
14+
while dq and nums[i] >= nums[dq[-1]]:
15+
dq.pop()
16+
dq.append(i)
17+
18+
res.append(nums[dq[0]])
19+
20+
for i in range(k, len(nums)):
21+
if dq and dq[0] == i - k:
22+
dq.popleft()
23+
while dq and nums[i] >= nums[dq[-1]]:
24+
dq.pop()
25+
26+
dq.append(i)
27+
res.append(nums[dq[0]])
28+
29+
return res
30+

0 commit comments

Comments
 (0)