Skip to content

Commit e19d04a

Browse files
Add sliding window maximum solution with tests
Implemented the `max_sliding_window` function to solve the sliding window maximum problem using a heap. Included a unit test to verify the implementation against a test case for correctness.
1 parent 84a7ab3 commit e19d04a

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# https://neetcode.io/problems/sliding-window-maximum
2+
3+
import unittest
4+
from typing import List
5+
import heapq
6+
7+
def max_sliding_window(nums: List[int], k: int) -> List[int]:
8+
result = []
9+
heap = []
10+
11+
for i, num in enumerate(nums):
12+
heapq.heappush(heap, (-num, i)) # Add number to the current window maximum
13+
14+
if i >= k - 1: # Did we fall outside the window?
15+
while heap[0][1] <= i - k: # Shrink the window
16+
heapq.heappop(heap)
17+
18+
result.append(-heap[0][0]) # Add the current maximum in the window to the result
19+
20+
return result
21+
22+
class Test(unittest.TestCase):
23+
def test_max_sliding_window(self):
24+
self.assertEqual(max_sliding_window([1, 2, 1, 0, 4, 2, 6], 3), [2, 2, 4, 4, 6])

0 commit comments

Comments
 (0)