package leetcode;

import java.util.Arrays;
import java.util.Stack;

/**
 * https://leetcode.com/problems/next-greater-element-ii/
 */
public class Problem503 {
    public int[] nextGreaterElements(int[] nums) {
        int[] answer = new int[nums.length];
        Stack<Integer> stack = new Stack<>();
        for (int i = nums.length - 1; i >= 0; i--) {
            while (!stack.isEmpty() && nums[i] > stack.peek()) {
                stack.pop();
            }
            if (!stack.isEmpty()) {
                answer[i] = stack.peek();
            } else {
                answer[i] = -1;
            }
            stack.push(nums[i]);
        }
        return answer;
    }

    public static void main(String[] args) {
        Problem503 prob = new Problem503();
        System.out.println(Arrays.toString(prob.nextGreaterElements(new int[]{1, 2, 1}))); // [2,-1,2]
        System.out.println(Arrays.toString(prob.nextGreaterElements(new int[]{1, 2, 1, 1}))); // [2,-1,2,2]
    }
}

@@ -16,33 +16,8 @@
 e;%0A%0A
-import java.util.Arrays;%0A
 impo
@@ -195,140 +195,453 @@
  int
-%5B%5D answer = new int%5Bnums.length%5D;%0A        Stack%3CInteger%3E stack = new Stack%3C%3E();%0A        for (int i = nums.length - 1; i %3E= 0; i--) %7B
+ max = Integer.MIN_VALUE;%0A        int maxIdx = 0;%0A        for (int i = 0; i %3C nums.length; i++) %7B%0A            if (max %3C nums%5Bi%5D) %7B%0A                max = nums%5Bi%5D;%0A                maxIdx = i;%0A            %7D%0A        %7D%0A        int%5B%5D answer = new int%5Bnums.length%5D;%0A        Stack%3CInteger%3E stack = new Stack%3C%3E();%0A        for (int i = maxIdx, j = 0; j %3C nums.length; i--, j++) %7B%0A            if (i %3C 0) %7B%0A                i = nums.length - 1;%0A            %7D
 %0A   
@@ -685,16 +685,17 @@
 ums%5Bi%5D %3E
+=
  stack.p
@@ -966,314 +966,7 @@
    %7D
-%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem503 prob = new Problem503();%0A        System.out.println(Arrays.toString(prob.nextGreaterElements(new int%5B%5D%7B1, 2, 1%7D))); // %5B2,-1,2%5D%0A        System.out.println(Arrays.toString(prob.nextGreaterElements(new int%5B%5D%7B1, 2, 1, 1%7D))); // %5B2,-1,2,2%5D%0A    %7D
 %0A%7D%0A

Solve problem 503