Java Solution


  • 0
    Y
    Circular loop from the element next to the maximum. The rest of the problem is the same as Next Greater Element I.
    public class Solution {
        public int[] nextGreaterElements(int[] nums) {
            int[] ans = new int[nums.length];
            if (nums.length == 0) return ans;
            Arrays.fill(ans, -1);
            int max = Integer.MIN_VALUE;
            int p = -1;
            for (int i = 0; i < nums.length; i ++) {
                if (nums[i] > max) {
                    max = nums[i];
                    p = i;
                }
            }
            helper(nums, ans, (p + 1) % nums.length);
            return ans;
        }
        
        private void helper(int[] nums, int[] ans, int s) {
            Stack<Integer> stack = new Stack<Integer>();
            boolean first = true;
            for (int i = s; i != s || first; i = (i + 1) % nums.length) {
                first = false;
                while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
                    ans[stack.pop()] = nums[i];
                }
                stack.push(i);
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.