Add sliding window maximum using monotonic deque#14133
Add sliding window maximum using monotonic deque#14133poyea merged 3 commits intoTheAlgorithms:masterfrom
Conversation
|
Hi maintainers! @poyea @cclauss @mindaugl
Ready for review! Would appreciate any feedback |
| from collections import deque | ||
|
|
||
|
|
||
| def sliding_window_maximum(numbers: list[int], window_size: int) -> list[int]: |
There was a problem hiding this comment.
What's the difference between this and maths/max_sum_sliding_window.py?
There was a problem hiding this comment.
Hi @poyea, thanks for the review!
Great question — these two are related (both use sliding window idea), but they solve completely different problems:
-
maths/max_sum_sliding_window.pyfinds the maximum sum of any single window of sizek→ returns one integer (the largest possible sum among all k-sized subarrays). It uses a simple running sum technique. -
My PR adds
other/sliding_window_maximum.pywhich finds the maximum element in every sliding window of sizek→ returns a list of max values (one per window position). This is the classic "Sliding Window Maximum" problem (LeetCode 239), solved efficiently with a monotonic deque to track the current maximum in O(1) per step.
Example to show the difference:
Input: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
- Your existing file would return the single max sum (e.g. max of 1+3+(-1)=3, 3+(-1)+(-3)=-1, etc. → probably 5+3+6=14)
- My new file returns [3, 3, 5, 5, 6, 7] — the max element in each of the 6 overlapping windows
They have different outputs, different goals, and use different internal logic (deque vs simple sum update). No overlap/duplication — this adds a popular, missing hard problem from LeetCode/competitive programming.
Happy to make any adjustments or add more comments if needed!
Implements the classic sliding window maximum problem (LeetCode 239) using a monotonic deque for O(n) time.
Features:
Ready for review!