Any other optimized solution?

//any other efficient approach??
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 temp[]=new int[2
n];
for(int i=0;i<temp.length;i++){
temp[i]=arr[i%n];
}
Stack s=new Stack<>();
ArrayList al=new ArrayList<>();
al.add(0,-1);
int tn=temp.length;
s.push(temp[tn-1]);
for(int i=tn-2;i>=0;i–){
while(!s.isEmpty()&&s.peek()<=temp[i]){
s.pop();
}
int val=s.isEmpty()?-1:s.peek();
al.add(0,val);
s.push(temp[i]);
}
for(int i=0;i<n;i++){
System.out.print(al.get(i)+" ");
}

}

}

@Vipin_coder,
You code is absolutely correct.

Only change you can think to do is use an array instead of arraylist, but arraylist is also fine.

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.