<p>Given a positive integer <code>n</code>, find <em>the smallest integer which has exactly the same digits existing in the integer</em> <code>n</code> <em>and is greater in value than</em> <code>n</code>. If no such positive integer exists, return <code>-1</code>.</p>

<p><strong>Note</strong> that the returned integer should fit in <strong>32-bit integer</strong>, if there is a valid answer but it does not fit in <strong>32-bit integer</strong>, return <code>-1</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 12
<strong>Output:</strong> 21
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 21
<strong>Output:</strong> -1
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>
</ul>

class Solution {
public:
    int nextGreaterElement(long long int n) {
        vector<long long int> digits;
        while (n) {
            digits.push_back(n % 10);
            n /= 10;
        }
        for (int i = 1, j, len = digits.size(), lmt = INT_MAX / 2 - 1; i < len;
             i++) {
            if (digits[i - 1] > digits[i]) {
                j = 0;
                while (digits[j] <= digits[i]) {
                    j++;
                }
                swap(digits[j], digits[i]);

                sort(begin(digits), begin(digits) + i, greater<int>());

                while (digits.size()) {
                    n = n * 10 + digits.back();
                    digits.pop_back();

                    if (n > lmt && digits.size())
                        return -1;
                }
                return n > INT_MAX ? -1 : n;
            }
        }
        return -1;
    }
};
7200