
Problem
Solution
Submissions
Sliding Window Maximum
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C++ program to solve the Sliding Window Maximum problem. You are given an array of integers `nums` and an integer `k`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position, return the maximum element in the sliding window.
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 data structure to track the maximum element in the current window.
- Step 2: Slide the window through the array, one position at a time.
- Step 3: For each window position, record the maximum element: [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
- Step 4: Return the array of maximum values [3, 3, 5, 5, 6, 7].
Example 2
- Input: nums = [1], k = 1
- Output: [1]
- Explanation:
- Step 1: Create a data structure to track the maximum element in the current window.
- Step 2: There is only one element and one window of size 1.
- Step 3: The maximum in this window is 1.
- Step 4: Return the array with the single maximum value [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) where k is the window size
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
- Consider using a deque (double-ended queue) to track potential maximum values
- Maintain elements in the deque in decreasing order
- Remove elements that are outside the current window
- Remove smaller elements that won't be maximum in current or future windows
- The front of the deque will always contain the current window's maximum