You are given an array of integers nums, 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 max sliding window.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [3,3,5,5,6,7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
Example 2:
Input: nums = [1], k = 1 Output: [1]
Constraints:
1 <= nums.length <= 105-104 <= nums[i] <= 1041 <= k <= nums.length
Companies: Amazon, Microsoft, Uber
Related Topics:
Array, Queue, Sliding Window, Heap (Priority Queue), Monotonic Queue
Similar Questions:
- Minimum Window Substring (Hard)
- Min Stack (Medium)
- Longest Substring with At Most Two Distinct Characters (Medium)
- Paint House II (Hard)
- Jump Game VI (Medium)
- Maximum Number of Robots Within Budget (Hard)
- Maximum Tastiness of Candy Basket (Medium)
- Maximal Score After Applying K Operations (Medium)
Assume the array is [3, 1, 2, ...] and k = 3, popping 3 out of the window will result in max value update, but popping 1 won't. This means that we can just keep track of [3, 2], i.e. a monotonically decreasing sequence of values.
Here we store the index of the monotonoically decreasing sequence. When a new value A[i] is added to the window, we pop the trailing index in the deque which are pointing to values that are smaller or equal to A[i]. Then we can push i into the deque.
We need to pop the index which falls out of the window from the deque as well.
// OJ: https://leetcode.com/problems/sliding-window-maximum
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& A, int k) {
vector<int> ans;
deque<int> q;
for (int i = 0; i < A.size(); ++i) {
while (q.size() && A[q.back()] <= A[i]) q.pop_back();
q.push_back(i);
if (q.front() == i - k) q.pop_front();
if (i >= k - 1) ans.push_back(A[q.front()]);
}
return ans;
}
};Similar to Solution 1, but here we store the values instead of the indexes in the deque.
// OJ: https://leetcode.com/problems/sliding-window-maximum/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& A, int k) {
deque<int> q;
vector<int> ans;
for (int i = 0; i < A.size(); ++i) {
if (i >= k && q.size() && q.front() == A[i - k]) q.pop_front();
while (q.size() && q.back() < A[i]) q.pop_back();
q.push_back(A[i]);
if (i >= k - 1) ans.push_back(q.front());
}
return ans;
}
};