Sliding Window Maximum
Sliding Window Maximum
Given an integer array nums and a window size k, return the maximum element in each sliding window of size k as the window moves from left to right. For an array of size n, there are n-k+1 windows. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=8, k=3, nums=[1 3 -1 -3 5 3 6 7] → "3 3 5 5 6 7"
Input format — only if your code reads from stdin
Input format (stdin): - First line: two integers n (array size) and k (window size) - Second line: n space-separated integers Output: the maximums for each window position, space-separated on a single line.
Approach
Monotonic deque: maintain a deque of indices where values are decreasing. For each new element, pop from the back any index whose value is ≤ current (they can never be the max). Pop from the front any index that has left the window. The front is always the current window's maximum.
Input
Output
- •
1 ≤ k ≤ n ≤ 10^5, -10^4 ≤ nums[i] ≤ 10^4
More Arrays problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards