Strongest fighter Stacks and Queues

import java.util.*;

public class Main{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
int k = sc.nextInt();
int[] ans = slidingMax(arr,k);
for(int i=0;i<ans.length;i++) {
System.out.print(ans[i]+" ");
}

    }

	public static int[] slidingMax(int[] a,int k){
		Deque<Integer> dq = new LinkedList<>();
		int n = a.length;
		int i = 0;
		int[] ans = new int[n-k+1];
		if(n<=1) {
			return a;
		}
		
		for( ;i<k;i++) {
		while(!dq.isEmpty()&&a[dq.peekLast()]<=a[i]) {
			dq.removeLast();
		}
		dq.addLast(i);
	}
		for(;i<n;i++) {
			ans[i-k] = a[dq.peekFirst()];
			while(!dq.isEmpty()&&dq.peekFirst()<=i-k) {
				dq.removeFirst();
			}
			
			while(!dq.isEmpty()&&a[dq.peekLast()]<=a[i]) {
				dq.removeLast();
			}
			dq.addLast(i);

		}
		ans[i-k] = a[dq.peekFirst()];
		return ans;
	}
}

//I’m getting time limit in 7 0f 10 cases . Can you pls check wherecan it be

@Siddharth_sharma1808,
Here is your corrected code: https://ide.codingblocks.com/s/217208

Your logic was correct and implementation too. I have used a faster Input/Output format in java called the Reader class instead of the scanner class. The scanner class is very slow inputs as compared to Reader class.

I would say the fastest way but is not recommended since it requires very cumbersome methods in its implementation.

It uses inputDataStream to read through the stream of data and uses read() method and nextInt() methods for taking inputs. This is by far the fastest ways of taking input but is difficult to remember and is cumbersome in its approach.

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.