0

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+" ");
    }
}

}

Manu Sharma
  • 467
  • 5
  • 15
  • 1
    Put this question on code review not stack overflow; code reviewers answer these questions a lot better. – Sean May 24 '18 at 18:06
  • 1
    Heres a hint: if you go left-to-right, you can keep track of the largest `x` very easily. If you go right-to-left, you can keep track of the smallest `y` very easily. This problem should be solveable with only 2 loops, resulting in O(n). – Obicere May 24 '18 at 18:20
  • The best way to reduce a O(n^2) is to go to O(n * log n), which is usually archieved by puting data in a hashmap and consulting it. – Sebastian D'Agostino May 24 '18 at 18:40

0 Answers0