-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextGreaterElementIII.cpp
More file actions
50 lines (43 loc) · 1.2 KB
/
Copy pathNextGreaterElementIII.cpp
File metadata and controls
50 lines (43 loc) · 1.2 KB
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
class Solution {
public:
int nextGreaterElement(int n) {
string s, t, u = "";
s = to_string(n);
t = "";
n = (int) s.size();
for (int i = n - 1; i > 0; i--) {
//db(s[i],s[i-1]);
if (s[i] <= s[i - 1]) {
t += s[i];
//db(t);
//cout<<endl;
} else {
t += s[i];
sort(t.begin(), t.end());
for (int j = 0; j < (int) t.size(); j++) {
//db(t[j],s[i-1]);
if (t[j] > s[i - 1]) {
char p = t[j];
t.erase(j, 1);
t += s[i - 1];
sort(t.begin(), t.end());
//u=t;
for (int k = 0; k < i - 1; k++)
u += s[k];
u += p;
u += t;
stringstream geek(u);
long long x = 0;
geek >> x;
if (x > INT_MAX) //To check if there is 'int'eger overflow
return -1;
return (int) x;
}
}
}
}
return -1;
}
};
//https://leetcode.com/problems/next-greater-element-iii/submissions/
//Alternative - https://www.geeksforgeeks.org/find-next-greater-number-set-digits/