I modified the code.
Now I am getting time limit exceeded.
Can someone suggest a way of optimizing the solution.
import java.util.;
import java.lang.;
class Main
{
static Stack stack1=new Stack();
static Stack stack2=new Stack();
static Stack stack3=new Stack();
static Stack stack4=new Stack();
static Stack stack5=new Stack();
static int d1=0;
static int d2=0;
public static void main (String[] args) throws java.lang.Exception
{
try {
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
sc.nextLine();
for(int i=0;i<T;i++)
{
boolean flag=false;
d1=0;
int N=sc.nextInt();
sc.nextLine();
for(int j=0;j<N;j++)
{
stack1.push(sc.nextInt());
}
if(N==1)
{
System.out.print(stack1.pop());
System.out.println();
continue;
}
while(!stack1.isEmpty())
{
int peek1=(int)stack1.peek();
stack1.pop();
stack2.push(peek1);
int peek2=(int)stack1.peek();
if(peek1>peek2)
{
d1=peek2;
flag=true;
break;
}
}
if(flag==false)
{
System.out.println("-1");
}
int curd2=Integer.MAX_VALUE;
while(!stack2.isEmpty())
{
int peek1=(int)stack2.peek();
stack2.pop();
if(peek1<curd2 && peek1>d1)
{
curd2=peek1;
}
else
{
stack3.push(peek1);
}
}
d2=curd2;
stack1.pop();
stack1.push(d2);
while (!stack3.isEmpty())
{
// pop out the first element
int tmp = (int)stack3.peek();
stack3.pop();
// while temporary stack is not empty and top
// of stack is greater than temp
while (!stack4.isEmpty() && (int)stack4.peek() < tmp)
{
// pop from temporary stack and push
// it to the input stack
stack3.push(stack4.peek());
stack4.pop();
}
// push temp in tempory of stack
stack4.push(tmp);
}
// System.out.println(“stack1:”+stack1+":stack2:"+stack2+“stack3:”+stack3+":d1:"+d1+“d2:”+d2);
// System.out.println(stack4);
while(!stack4.isEmpty())
{
stack1.push(stack4.peek());
stack4.pop();
}
stack1.push(d1);
// System.out.println(“stack1:”+stack1+":stack2:"+stack2+“stack3:”+stack3+":d1:"+d1+“d2:”+d2);
while(!stack1.isEmpty())
{
stack5.push(stack1.peek());
stack1.pop();
}
while(!stack5.isEmpty())
{
System.out.print(stack5.pop());
}
System.out.println();
}
} catch(Exception e) {
e.printStackTrace();
// System.out.println(“stack1:”+stack1+":stack2:"+stack2+“stack3:”+stack3+":d1:"+d1+“d2:”+d2);
} finally {
}
}
}