Skip to content

Commit 7047193

Browse files
Refactor sliding window maximum function parameters
Updated the method to use 'window_size' instead of 'k' for clarity. Added docstring examples for better understanding.
1 parent f53b67d commit 7047193

File tree

1 file changed

+19
-30
lines changed

1 file changed

+19
-30
lines changed
Lines changed: 19 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,42 @@
1-
"""
2-
Question:
3-
Given an integer array nums and an integer k, return the maximum value in each sliding window of size k.
4-
5-
Example:
6-
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
7-
Output: [3,3,5,5,6,7]
8-
Explanation:
9-
Window positions and max values:
10-
[1,3,-1] -> max = 3
11-
[3,-1,-3] -> max = 3
12-
[-1,-3,5] -> max = 5
13-
[-3,5,3] -> max = 5
14-
[5,3,6] -> max = 6
15-
[3,6,7] -> max = 7
16-
"""
17-
181
from collections import deque
192
from typing import List
203

21-
224
class SlidingWindowMaximum:
23-
def max_sliding_window(self, nums: List[int], k: int) -> List[int]:
5+
"""
6+
Problem:
7+
Given an integer array and a window_size, return the maximum value in each
8+
sliding window of that size.
9+
10+
Example:
11+
>>> solver = SlidingWindowMaximum()
12+
>>> solver.max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3)
13+
[3, 3, 5, 5, 6, 7]
14+
"""
15+
16+
def max_sliding_window(self, nums: List[int], window_size: int) -> List[int]:
2417
if not nums:
2518
return []
2619

27-
result = [] # Stores max of each window
28-
window = deque() # Stores indices of elements in current window
20+
result = []
21+
window = deque()
2922

3023
for i, num in enumerate(nums):
31-
# Remove indices of elements outside current window
32-
while window and window[0] <= i - k:
24+
while window and window[0] <= i - window_size:
3325
window.popleft()
3426

35-
# Remove indices of elements smaller than current num
3627
while window and nums[window[-1]] < num:
3728
window.pop()
3829

3930
window.append(i)
4031

41-
# Add the max for this window to result
42-
if i >= k - 1:
32+
if i >= window_size - 1:
4333
result.append(nums[window[0]])
4434

4535
return result
4636

4737

48-
# Example dry run
4938
if __name__ == "__main__":
50-
nums = [1, 3, -1, -3, 5, 3, 6, 7]
51-
k = 3
5239
solver = SlidingWindowMaximum()
53-
print("Sliding Window Maximum:", solver.max_sliding_window(nums, k))
40+
print("Sliding Window Maximum:",
41+
solver.max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3))
42+

0 commit comments

Comments
 (0)