|
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 | | - |
18 | 1 | from collections import deque |
19 | 2 | from typing import List |
20 | 3 |
|
21 | | - |
22 | 4 | 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]: |
24 | 17 | if not nums: |
25 | 18 | return [] |
26 | 19 |
|
27 | | - result = [] # Stores max of each window |
28 | | - window = deque() # Stores indices of elements in current window |
| 20 | + result = [] |
| 21 | + window = deque() |
29 | 22 |
|
30 | 23 | 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: |
33 | 25 | window.popleft() |
34 | 26 |
|
35 | | - # Remove indices of elements smaller than current num |
36 | 27 | while window and nums[window[-1]] < num: |
37 | 28 | window.pop() |
38 | 29 |
|
39 | 30 | window.append(i) |
40 | 31 |
|
41 | | - # Add the max for this window to result |
42 | | - if i >= k - 1: |
| 32 | + if i >= window_size - 1: |
43 | 33 | result.append(nums[window[0]]) |
44 | 34 |
|
45 | 35 | return result |
46 | 36 |
|
47 | 37 |
|
48 | | -# Example dry run |
49 | 38 | if __name__ == "__main__": |
50 | | - nums = [1, 3, -1, -3, 5, 3, 6, 7] |
51 | | - k = 3 |
52 | 39 | 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