738. Monotone Increasing Digits
Input: N = 10
Output: 9Input: N = 1234
Output: 1234Input: N = 332
Output: 299// Greedy
int monotoneIncreasingDigits(int N) { // time: O(n); space: O(n)
string str = to_string(N);
int n = str.length(), pos = n;
for (int i = n - 1; i >= 0; --i) {
if (str[i - 1] <= str[i]) continue;
pos = i;
--str[i - 1];
}
for (int j = pos; j < n; ++j) {
str[j] = '9';
}
return stoi(str);
}Last updated