
Problem
Solution
Submissions
Sliding Window Maximum using Deque
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to find the maximum element in each sliding window of size k in an array. Given an array of integers nums and a window size k, return an array of maximum values for each window as it slides from left to right.
Example 1
- Input: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
- Output: [3, 3, 5, 5, 6, 7]
- Explanation:
Step 1: The sliding window has size k = 3
Step 2: Window 1: [1, 3, -1] → max = 3
Step 3: Window 2: [3, -1, -3] → max = 3
Step 4: Window 3: [-1, -3, 5] → max = 5
Step 5: Window 4: [-3, 5, 3] → max = 5
Step 6: Window 5: [5, 3, 6] → max = 6
Step 7: Window 6: [3, 6, 7] → max = 7
Example 2
- Input: nums = [1, -1], k = 1
- Output: [1, -1]
- Explanation:
Step 1: The sliding window has size k = 1
Step 2: Window 1: [1] → max = 1
Step 3: Window 2: [-1] → max = -1
Constraints
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
- 1 <= k <= nums.length
- Time Complexity: O(n) where n is the length of the array
- Space Complexity: O(k)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a deque (double-ended queue) to maintain potential maximum elements.
- Keep the deque in decreasing order of values.
- The front of the deque will always contain the maximum element of the current window.
- When sliding the window, remove elements from the front if they are outside the window.
- Before adding a new element, remove elements from the back that are smaller than the new element.
- This ensures that the deque is always in decreasing order and contains only elements from the current window.