Where is the mistake in this code . I am getting TLE .
import java.util.*;
public class Main {
public static void main(String args[]) {
// Your Code Here
Scanner scan = new Scanner(System.in) ;
int n = scan.nextInt() ;
long[] arr = new long[n] ;
for(int i = 0 ; i < n ; i ++){
arr[i] = scan.nextLong() ;
}
nextGreater(arr) ;
}
public static void nextGreater(long[] arr){
Stack<Long> stack = new Stack<Long>() ;
for(int i = 0 ; i < arr.length ; i ++){
while(!stack.isEmpty() && arr[i] >stack.peek()){
stack.pop() ;
System.out.print(arr[i]+" ") ;
}
stack.push(arr[i]) ;
}
// checking greater element for the last element in the array
for(int i = 0 ; i <= arr.length-2 ; i ++){
if(arr[i] >stack.peek()){
stack.pop() ;
System.out.print(arr[i]+" ") ;
}
}
if(!stack.isEmpty()){
while(!stack.isEmpty()){
System.out.print(-1+" ") ;
}
}
}
}