give wrong answer
Maximum element in every window of size
Hey @khemchandrs
You need to replace
while(!(dq.empty()) && A[i]>=dq.back())
with
while(!(dq.empty()) && A[i]>=A[dq.back()])
because dq.back() denotes the index of element at the back(we’re storing indexes in the queue), and we need to compare with element present at that index i. e. A[dq.back()]
Here’s your altered code which should work:
#include
using namespace std;
#include
void maxKthArray(int *A,int n,int k){
deque<int> dq;
int i;
for(i=0;i<k;i++){
while( (!dq.empty()) && A[i]>=A[dq.back()]){
dq.pop_back();
}
dq.push_back(i);
}
for(;i<n;i++){
cout<<A[dq.front()]<<" ";
while(!(dq.empty()) && dq.front()<=(i-k) ){
dq.pop_front();
}
while(!(dq.empty()) && A[i]>=A[dq.back()]){
dq.pop_back();
}
dq.push_back(i);
}
cout<<A[dq.front()];
}
int main(){
int A[]={3,5,2,2,7};
maxKthArray(A,5,3);
}
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.