Monotone Increasing Digits - Problem
A number has monotone increasing digits if each digit is less than or equal to the next digit when reading from left to right. For example,
Given an integer
Key Challenge: When we encounter a digit that violates the monotone property (i.e., a digit is greater than the next digit), we need to strategically reduce it and set all subsequent digits to 9 to maximize the result.
1234 and 1333 have monotone increasing digits, but 4321 and 1232 do not.Given an integer
n, your task is to find the largest number that is less than or equal to n and has monotone increasing digits. This is a classic greedy algorithm problem where we need to make optimal local choices to achieve the global maximum.Key Challenge: When we encounter a digit that violates the monotone property (i.e., a digit is greater than the next digit), we need to strategically reduce it and set all subsequent digits to 9 to maximize the result.
Input & Output
example_1.py โ Python
$
Input:
n = 10
โบ
Output:
9
๐ก Note:
The number 10 has digits [1, 0], where 1 > 0, so it doesn't have monotone increasing digits. The largest number โค 10 with monotone increasing digits is 9.
example_2.py โ Python
$
Input:
n = 1332
โบ
Output:
1299
๐ก Note:
The number 1332 has digits [1, 3, 3, 2]. Since 3 > 2, we need to fix this. We decrement the first 3 to get 2, then set all following digits to 9, resulting in 1299.
example_3.py โ Python
$
Input:
n = 54321
โบ
Output:
49999
๐ก Note:
This number has multiple violations (5>4>3>2>1). Starting from right, we find 2>1, fix it to get 54319. Then 3>1, fix to get 54299. Continue this process until we get 49999.
Constraints
- 0 โค n โค 109
- The result will always fit in a 32-bit integer
- Time limit: 1 second per test case
Visualization
Tap to expand
Understanding the Visualization
1
Inspect the Blueprint
Start with your target staircase design (the input number)
2
Scan for Problems
Check from right to left for steps that violate the height rule
3
Fix Violations
When you find a step that's too high, lower it by one unit
4
Maximize Remaining
Set all steps to the right to maximum height (9) to get the tallest valid staircase
Key Takeaway
๐ฏ Key Insight: Work backwards from right to left. When you find a violation, make the minimal fix (decrement by 1) and maximize everything to the right (set to 9). This greedy approach guarantees the largest possible valid result.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code