Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find overall max element to the left of each element in an arrray (not the first max)

I’m trying to find the max element to the left of each element but i could write code for only the first max.

public static void main(String[] args) {
        int a[]={3,0,0,2,0,4};
        Stack<Integer> st=new Stack<Integer>();
        ArrayList<Integer> al=new ArrayList<>();
        for(int i=0;i<5;i++){
            while(st.size()>0 && a[st.peek()]<a[i]){
                st.pop();
            }
            if(st.empty()) al.add(a[i]);
            else al.add(a[st.peek()]);

            st.push(i);
        }
        System.out.println(al);
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Using Stack

public static int[] maxLeftElement(int[] A)
{
    final int n = A.length;
    int[] ans = new int[n];

    Stack<Integer> S = new Stack<>();
    S.push(A[0]);

    for (int i = 0;i <  n;i++)
    {   
        if (S.peek() <= A[i]) 
        {
            S.pop();
            S.push(A[i]);
        }
        
        ans[i] = S.peek();
    }

    return ans;
}

Efficient Solution

In the above solution, there will be only one element in the stack throughout the execution of the function. Hence, it is quite clear to observe the stack does not offer any benefit whatsoever. Hence, it is better to replace it with a simple int.

public static int[] maxLeftElement(int[] A)
{
    final int n = A.length;
    int[] ans = new int[n];

    int maxSoFar = A[0];
    for (int i = 0;i <  n;i++)
    {
        maxSoFar = Math.max(maxSoFar,A[i]);
        ans[i] = maxSoFar;
    }

    return ans;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading