
Problem
Solution
Submissions
Sliding Window Maximum
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to find the maximum element in every sliding window of size k in an array. Given an array of integers and a window size k, slide the window from left to right and return an array containing the maximum element in each window position.
Example 1
- Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
- Output: [3,3,5,5,6,7]
- Explanation:
- Window [1,3,-1] -> maximum is 3.
- Window [3,-1,-3] -> maximum is 3.
- Window [-1,-3,5] -> maximum is 5.
- Continue sliding and finding maximum in each window.
- Window [1,3,-1] -> maximum is 3.
Example 2
- Input: nums = [1], k = 1
- Output: [1]
- Explanation:
- Only one element in array and window size is 1.
- The maximum (and only) element in the window is 1.
- Result array contains single element [1].
- Only one element in array and window size is 1.
Constraints
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
- 1 <= k <= nums.length
- Time Complexity: O(n) using deque approach
- Space Complexity: O(k) for storing indices in deque
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 (implemented with array) to store indices of array elements
- The deque will store indices in decreasing order of their corresponding values
- The front of deque always contains the index of maximum element in current window
- Remove indices that are out of current window from front of deque
- Remove indices from rear of deque if their values are smaller than current element
- Add current element's index to rear of deque and store front element as maximum