We want the largest number ≤ n with digits in non-decreasing order. If a digit is greater than the next, we decrease it and set all following digits to 9.
Convert n to a list of digits. Scan from left to right, find the first place where digits[i] > digits[i+1], decrease digits[i] by 1, set all digits after i to 9, and repeat if needed. Convert back to integer.
classSolution {
publicintmonotoneIncreasingDigits(int n) {
char[] digits = Integer.toString(n).toCharArray();
int mark = digits.length;
for (int i = digits.length- 1; i > 0; i--) {
if (digits[i]< digits[i-1]) {
digits[i-1]--;
mark = i;
}
}
for (int i = mark; i < digits.length; i++) {
digits[i]='9';
}
return Integer.parseInt(new String(digits));
}
}
1
2
3
4
5
6
7
8
9
10
defmonotoneIncreasingDigits(n):
digits = list(str(n))
mark = len(digits)
for i in range(len(digits)-1, 0, -1):
if digits[i] < digits[i-1]:
digits[i-1] = str(int(digits[i-1]) -1)
mark = i
for i in range(mark, len(digits)):
digits[i] ='9'return int(''.join(digits))