The given code gives correct output but exceeds the time limit and I have no idea how to optimize it. I know it is of O(n^2) complexity but I am not able to get anywhere near to optimizing it. Even a few hints would be appreciated.
The question was Question
import java.util.*;
import java.io.*;
class Alpha{
public static void main(String args[]) throws IOException
{
int n=0,i=0,x=-1,y=-1,sum=0,m1,m2;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n=Integer.parseInt(st.nextToken());
Stack<Integer> stk=new Stack<>();
long arr[] = new long[n];
String str[]=br.readLine().split(" ");
for(i=0;i<n;i++)
{
arr[i]=Long.parseLong(str[i]);
}
for(i=n-1;i>=0;i--)
{
x=-1;
y=-1;
for(int j=i-1;j>=0;j--)
{
if(arr[j]>arr[i])
{
x=j+1;
break;
}
}
stk.push(x);
for(int j=i+1;j<n;j++)
{
if(arr[j]>arr[i])
{
y=j+1;
break;
}
}
stk.push(y);
}
while(!stk.isEmpty())
{
m1=stk.peek();
stk.pop();
m2=stk.peek();
stk.pop();
sum=m1+m2;
System.out.print(sum+" ");
}
}
}