Sliding Window Maximum - Problem
You are given an array of integers nums and a sliding window of size k which moves from the leftmost position to the rightmost position. At each position, you can only see the k numbers in the window.
Each time the sliding window moves right by one position, find the maximum element in the current window.
Return an array containing the maximum value of each window position.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,3,-1,-3,5,3,6,7], k = 3
›
Output:
[3,3,5,5,6,7]
💡 Note:
Window [1,3,-1] → max=3, [3,-1,-3] → max=3, [-1,-3,5] → max=5, [-3,5,3] → max=5, [5,3,6] → max=6, [3,6,7] → max=7
Example 2 — Single Element Window
$
Input:
nums = [1], k = 1
›
Output:
[1]
💡 Note:
Only one element, so maximum is itself
Example 3 — All Same Elements
$
Input:
nums = [7,7,7,7], k = 2
›
Output:
[7,7,7]
💡 Note:
All elements are same, so every window has maximum 7
Constraints
- 1 ≤ nums.length ≤ 105
- -104 ≤ nums[i] ≤ 104
- 1 ≤ k ≤ nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,3,-1,-3,5,3,6,7] with window size k=3
2
Process
Slide window left to right, find maximum in each position
3
Output
Array of maximums [3,3,5,5,6,7]
Key Takeaway
🎯 Key Insight: Use a deque to maintain potential maximums in decreasing order, avoiding redundant comparisons
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code