package leetcode;

/**
 * https://leetcode.com/problems/next-greater-element-iii/
 */
public class Problem556 {
    public int nextGreaterElement(int n) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem556 prob = new Problem556();
        System.out.println(prob.nextGreaterElement(12)); // 21
        System.out.println(prob.nextGreaterElement(21)); // -1
        System.out.println(prob.nextGreaterElement(14526)); // 14562
        System.out.println(prob.nextGreaterElement(14526)); // 14562
        System.out.println(prob.nextGreaterElement(1452)); // 1524
        System.out.println(prob.nextGreaterElement(14520)); // 15024
        System.out.println(prob.nextGreaterElement(1002)); // 1020
        System.out.println(prob.nextGreaterElement(1233)); // 1323
        System.out.println(prob.nextGreaterElement(4321)); // -1
    }
}

@@ -12,16 +12,42 @@
 tcode;%0A%0A
+import java.util.Arrays;%0A%0A
 /**%0A * h
@@ -186,32 +186,770 @@
     
-// TODO%0A        return 0
+boolean found = false;%0A        char%5B%5D c = Integer.toString(n).toCharArray();%0A        for (int i = c.length - 1; i %3E 0; i--) %7B%0A            if (c%5Bi%5D %3E c%5Bi - 1%5D) %7B%0A                found = true;%0A                int nextGreater = c.length - 1;%0A                for (int j = c.length - 1; j %3E 0; j--) %7B%0A                    if (c%5Bi - 1%5D %3C c%5Bj%5D) %7B%0A                        nextGreater = j;%0A                        break;%0A                    %7D%0A                %7D%0A                char tmp = c%5BnextGreater%5D;%0A                c%5BnextGreater%5D = c%5Bi - 1%5D;%0A                c%5Bi - 1%5D = tmp;%0A                Arrays.sort(c, i, c.length);%0A                break;%0A            %7D%0A        %7D%0A        if (!found) %7B%0A            return -1;%0A        %7D%0A        return Integer.parseInt(new String(c))
 ;%0A  
@@ -1241,77 +1241,8 @@
 562%0A
-        System.out.println(prob.nextGreaterElement(14526)); // 14562%0A
     
@@ -1507,16 +1507,16 @@
 // 1323%0A
-
         
@@ -1568,20 +1568,158 @@
 21)); // -1%0A
+        System.out.println(prob.nextGreaterElement(12750)); // 15027%0A        System.out.println(prob.nextGreaterElement(16750)); // 17056%0A
     %7D%0A%7D%0A

Update problem 556