THIS code is not getting submitted but it is correct for most of the test cases so please tell me where I am wrong

static ArrayList max_of_subarrays(int arr[], int n, int k)
{
// Your code here
Queue pq = new LinkedList<>();
ArrayList ar = new ArrayList();
int i = 0;
int j = 0;
int max = -100000;
while(j < arr.length){
if(arr[j] > max){
while(!pq.isEmpty()){
pq.remove();
}
pq.add(arr[j]);
max = arr[j];

        }
        else
        pq.add(arr[j]);
        
        if(j == k+i-1){
            ar.add(pq.peek());
            if(arr[i] == pq.peek()){
            pq.remove();
            }
            i++;
            
        }
        j++;
        
                
    }
    return ar;

}

Link of my code --> https://ide.codingblocks.com/s/609883

Question Link–> https://practice.geeksforgeeks.org/problems/maximum-of-all-subarrays-of-size-k3101/1#

Hey @ayush_r18,

This logic used for adding the number as window maximum is incorrect as it isn’t giving the maximum element at the peek position.

Your code fails for this testcase.
10 3
1 3 1 2 1 4 5 2 3 6

The output obtained is : 3 3 1 4 5 5 5 6
which is incorrect as it should have been 2 instead of 1 but 1 lies as the peek element, thus you are getting the wrong answer.

The expected output is: 3 3 2 4 5 5 5 6

You can refer to the theory video to understand the correct approach.
Hope it helps.

1 Like

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.