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:
Click - to see solution code
- C++
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;
}
};