Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Sliding Window Maximum

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.

Brute force

Monotonic Queue

Code

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k)
    {
        int n = nums.size();
        vector<int> windowMax;
        deque<int> dq;
        for (int i = 0; i < n; i++) {
            // remove numbers from front which are out of window range k
            while (!dq.empty() && dq.front() < i - (k - 1))
                dq.pop_front();

            // remove smaller numbers in k range as they are useless
            while (!dq.empty() && nums[dq.back()] < nums[i])
                dq.pop_back();

            dq.push_back(i);

            // if index is greater than first k elements
            if (i >= k-1) windowMax.push_back(nums[dq.front()]);
        }
        return windowMax;
    }
};