Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:(similar to skyline problem)
- We will have a max heap and a map which will store the window elements as keys.
- first insert first window and find it's max and put into _max and answer vector.
- whenver you get a new number,push it into the queue,update the max and update
- the map.if max_element is same as the previous element before the start of window
- let's say prev, then it is possible that prev is not in the new window so get the
- maximum number present in the window using the max heap and map and update the
- _max and push it into the answer vector.
- */
- class Solution {
- public:
- vector<int> maxSlidingWindow(vector<int>& nums, int k) {
- unordered_map<int,int> mp;
- priority_queue<int> q;
- vector <int> ans;
- int _max=nums[0],i=0;
- for(i=0;i<k;i++){
- _max=max(_max,nums[i]);
- mp[nums[i]]++;
- q.push(nums[i]);
- }
- ans.push_back(_max);
- for(;i<nums.size();i++){
- q.push(nums[i]);
- _max=max(_max,nums[i]);
- mp[nums[i]]++;
- if(nums[i-k]==_max){
- mp[nums[i-k]]--;
- while(!mp[q.top()]){
- q.pop();
- }
- _max=q.top();
- }
- else{
- mp[nums[i-k]]--;
- }
- ans.push_back(_max);
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement