Solution using array as a stack Java


#1
public class Solution {
    public int[] nextGreater(int[] A) {
        int n=A.length;
        int[] nG=new int[n];
        nG[n-1]=-1;
        for(int i=n-1;i>0;i--){
            if(A[i]>A[i-1]){
                nG[i-1]=A[i];
            }else{
                if(A[i-1]<nG[i]){
                    nG[i-1]=nG[i];    
                }else{
                    int j=i;
                    while(j<n&&A[i-1]>=nG[j++]);
                    nG[i-1]=nG[j-1];
                }
            }
        }
        return nG;
    }
}