Find the Max Element, and use Stack to keep track O(2n) complexity
First find the maximum element in the array, it will always have a -1 for the answer to it\'s next greater element because no element is greater than that in th
First find the maximum element in the array, it will always have a -1 for the answer to it\'s next greater element because no element is greater than that in the array.\nThen, start a loop from that index till the same index in a backward direction, and fill the stack accordingly, if stack contains any lesser elements remove them, then check if stack is empty the answer will be -1 or else the top element of stack.\n\nTC: O(n) for finding the max element + O(n) for finding next greater elements of every element\nSC: O(n) at max the stack may contain n elements.\n\nJAVA:\n```class Solution {\n    public int[] nextGreaterElements(int[] nums) {\n        int pm = -1;\n        int max = Integer.MIN_VALUE;\n        for (int i = 0; i < nums.length; i++)\n            if (max < nums[i]) {\n                max = nums[i];\n                pm = i;\n            }\n        int[] res = new int[nums.length];\n        Stack<Integer> stk = new Stack<>();\n        int i = pm;\n        res[i] = -1;\n        stk.push(nums[i]);\n        i--;\n        if (i < 0)\n            i = nums.length - 1;\n        \n        while (i != pm) {\n            while (!stk.isEmpty() && stk.peek() <= nums[i]) \n                stk.pop();\n            if (stk.isEmpty())\n                res[i] = -1;\n            else\n                res[i] = stk.peek();\n            stk.push(nums[i]);\n            i--;\n            if (i < 0)\n                i = nums.length - 1;\n        }\n        return res;\n    }\n}
[]