imashutosh51

Monotone Increasing Digits

Jan 28th, 2026 (edited)
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. '''
  2. Intuition:
  3. A monotone increasing number never decreases from left to right.
  4. If a digit is bigger than the next one, the number becomes invalid.
  5. To fix this while staying ≤ n, we reduce the left digit by 1.
  6. Then we make all digits to the right as large as possible by setting them to 9.
  7. This gives the largest valid number not greater than n.
  8.  
  9. for eg. input=[3,3,2] so it's biggest monotone increasing would be 299 so observation you are taking the first place whose right element is not smaller than it and reduce it by 1 and all elements after that converted to 9 so do the same.
  10. '''
  11. class Solution:
  12.     def monotoneIncreasingDigits(self, n: int) -> int:
  13.         digits = list(map(int, str(n)))
  14.         mark = len(digits)
  15.         print(digits, mark)
  16.  
  17.         # Traverse from right to left
  18.         for i in range(len(digits) - 1, 0, -1): #we are doing from left to right bcz left to right will not consider the prev elements
  19.             if digits[i - 1] > digits[i]:
  20.                 digits[i - 1] -= 1 #we are only reducing this element by 1 so that mark and onwards can be 9 and that would be fine.
  21.                 mark = i
  22.  
  23.         # Set all digits after mark to 9
  24.         for i in range(mark, len(digits)):
  25.             digits[i] = 9
  26.  
  27.         return int("".join(map(str, digits)))
  28.  
Advertisement
Add Comment
Please, Sign In to add comment