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 :
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;
}