[LeetCode] Next Greater Element III

556. Next Greater Element III

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Solution {
private:
string getMax(map<char, int>& digits) {
stringstream ss;
for(char ch = '9'; ch >= '0'; ch--) {
for(int i = 0; i < digits[ch]; i++)
ss<<ch;
}
return ss.str();
}

void recursive(string& maxNum, string& num, map<char, int>& digits, string cur) {
if(cur.length() == maxNum.length()) {
long a = stol(maxNum), b = stol(num), c = stol(cur);
if(a > c && c > b)
maxNum = cur;
return;
}

for(char ch = '0'; ch <= '9'; ch++) {
if(digits[ch]) {
int pos;
int maxFlag = 0, minFlag = 0;
for(pos = 0; pos < cur.length(); pos++) {
if(maxFlag == 0) {
if(maxNum[pos] < cur[pos])
maxFlag = -1;
else if(maxNum[pos] > cur[pos])
maxFlag = 1;
}
if(minFlag == 0) {
if(num[pos] < cur[pos])
minFlag = 1;
else if(num[pos] > cur[pos])
minFlag = -1;
}
}
if(maxFlag == 0) {
maxFlag = maxNum[pos] - ch;
}

if(minFlag == 0) {
minFlag = ch - num[pos];
}

if(maxFlag >= 0 && minFlag >= 0) {
digits[ch]--;
recursive(maxNum, num, digits, cur + ch);
digits[ch]++;
}
}
}
return;
}
public:
int nextGreaterElement(int n) {
string num = to_string(n);
map<char, int> digits;
bool flag = true;
for(int i = 1; i < num.size(); i++) {
if(num[i] > num[i - 1])
flag = false;
digits[num[i]]++;
}
digits[num[0]]++;

if(flag)
return -1;

string maxNum = getMax(digits);
recursive(maxNum, num, digits, "");
long res = stol(maxNum);
return res > INT_MAX ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/27/PS/LeetCode/next-greater-element-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.