Maximum element in every window


i applied brute force approach for this problem and this is my source code …please make me understand why it is not working… :slight_smile:

Brute force is not the optimal solution for this question.Try solving this using priority queue/ deque and sliding window

This is my code for same question on leetcode(Question Name-Sliding window maximum)
class Solution {
public:
vector maxSlidingWindow(vector& nums, int k) {
int i,j;
vectorans;
priority_queue<pair<int,int>>q;
for(i=0;i<k;i++)
{
q.push(make_pair(nums[i],i));
}
ans.push_back(q.top().first);
for(i=k;i<nums.size();i++)
{
q.push(make_pair(nums[i],i));
if(q.top().second>=i-k+1&&q.top().second<=k)
{
ans.push_back(q.top().first);
}
else
{
while(q.top().second<i-k+1)q.pop();
ans.push_back(q.top().first);
}
}
return ans;
}
};

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.