StrongestFighter problem

Why this code is giving error?
import java.util.*;
public class Main {
public static void main(String args[]) throws Exception{
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
int[] a= new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
StrongestFighter(a,n,k);
}
public static void StrongestFighter(int a[], int n, int k)
{
int i=0;
Deque q = new LinkedList<>();
for(i=0;i<k;i++)
{
while(!q.isEmpty() && a[i]>a[q.peekLast()])
{
q.removeLast();
}
q.addLast(i);
}

	for( ;i<n;i++)
	{
	    System.out.print(a[q.peek()]+" ");
	    
	    while(!q.isEmpty() && q.peek()<=i-k)
	    {
	        q.removeFirst();
	    }
	    
	    while(!q.isEmpty() && a[i]>=a[q.peekLast()])
	   {
	       q.removeLast();
	   }
	   q.addLast(i);
	}
	System.out.print(a[q.peek()]);
}

}

@minal.251298,
https://ide.geeksforgeeks.org/qPbjeSEwVv : corrected code

2 errors:

  1. Input order. You have taken n,k,array. The correct order of input is n,array,k.
  2. while(!q.isEmpty() && a[i]>a[q.peekLast()]) in this line, it should be a[i]>=a[q.peekLast()]

It is still showing TLE in 2 testcases rest are correct

This code is still showing timelimit error

@minal.251298

try this code.i have used fastreader for i/o instead of scanner class.and it passes all the test cases comfortably in 5 seconds.scanner is fairly slow

1 Like