Skip to main content

Sliding Window Maximum

Problem

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.

Solution Approach

Expected Time complexity: O(nlog(n))O(nlog(n))

Click - to see solution code
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
map<int, int> mp;
for (int i = 0; i < k; i++) mp[nums[i]]++;
int n = nums.size();
vector<int> ans;
auto itr = mp.end();
itr--;
ans.push_back((*itr).first);
for (int i = k; i < n; i++) {
mp[nums[i]]++;
mp[nums[i - k]]--;
if (mp[nums[i - k]] == 0) {
mp.erase(nums[i - k]);
}
itr = mp.end();
itr--;
ans.push_back((*itr).first);
}

return ans;
}
};