Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

README.md

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] <= 104
  • 1 <= k <= nums.length

Companies: Amazon, Microsoft, Uber

Related Topics:
Array, Queue, Sliding Window, Heap (Priority Queue), Monotonic Queue

Similar Questions:

Solution 1. Mono-Deque

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;
    }
};

Solution 2. Mono-Deque

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;
    }
};