Advertisement
imashutosh51

Sliding Window Maximum

Oct 29th, 2022
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. /*
  2. Logic:(similar to skyline problem)
  3. We will have a max heap and a map which will store the window elements as keys.
  4. first insert first window and find it's max and put into _max and answer vector.
  5. whenver you get a new number,push it into the queue,update the max and update
  6. the map.if max_element is same as the previous element before the start of window
  7. let's say prev, then it is possible that prev is not in the new window so get the
  8. maximum number present in the window using the max heap and map and update the
  9. _max and push it into the answer vector.
  10. */
  11. class Solution {
  12. public:
  13.     vector<int> maxSlidingWindow(vector<int>& nums, int k) {
  14.         unordered_map<int,int> mp;
  15.         priority_queue<int> q;
  16.         vector <int> ans;
  17.         int _max=nums[0],i=0;
  18.         for(i=0;i<k;i++){
  19.             _max=max(_max,nums[i]);
  20.             mp[nums[i]]++;
  21.             q.push(nums[i]);
  22.         }
  23.         ans.push_back(_max);
  24.         for(;i<nums.size();i++){
  25.             q.push(nums[i]);
  26.             _max=max(_max,nums[i]);
  27.             mp[nums[i]]++;
  28.             if(nums[i-k]==_max){
  29.                 mp[nums[i-k]]--;
  30.                 while(!mp[q.top()]){
  31.                     q.pop();
  32.                 }
  33.                 _max=q.top();
  34.             }
  35.             else{
  36.                 mp[nums[i-k]]--;
  37.             }
  38.             ans.push_back(_max);
  39.         }
  40.         return ans;
  41.     }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement