
Problem
Solution
Submissions
Sliding Window Maximum
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C# program to implement the MaxSlidingWindow(int[] nums, int k)
function, which takes an array of integers nums and an integer k as input. The function should find the maximum element in each sliding window of size k and return an array of these maximums.
Example 1
- Input: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
- Output: [3, 3, 5, 5, 6, 7]
- Explanation:
- Step 1: Create a sliding window of size k and move it through the array.
- Step 2: For each window position, find the maximum element.
- Window [1, 3, -1] → maximum is 3
- Window [3, -1, -3] → maximum is 3
- Window [-1, -3, 5] → maximum is 5
- Window [-3, 5, 3] → maximum is 5
- Window [5, 3, 6] → maximum is 6
- Window [3, 6, 7] → maximum is 7
- Step 3: Return the array of maximum values [3, 3, 5, 5, 6, 7].
Example 2
- Input: nums = [9, 11, 8, 7, 6, 5], k = 3
- Output: [11, 11, 8, 7]
- Explanation:
- Step 1: Create a sliding window of size k and move it through the array.
- Step 2: For each window position, find the maximum element.
- Window [9, 11, 8] → maximum is 11
- Window [11, 8, 7] → maximum is 11
- Window [8, 7, 6] → maximum is 8
- Window [7, 6, 5] → maximum is 7
- Step 3: Return the array of maximum values [11, 11, 8, 7].
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 input array
- Space Complexity: O(k) for storing the deque of size 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 a window of potential maximum values
- Keep the deque in descending order to quickly find the maximum
- As you slide the window, remove elements that are outside the current window
- Also remove smaller elements from the back as they won't be needed
- The front of the deque always contains the maximum element of the current window