Program to find number not greater than n where all digits are non-decreasing in python

PythonServer Side ProgrammingProgramming

Suppose we have a number n, we have to find the largest number smaller or equal to n where all digits are non-decreasing.

So, if the input is like n = 221, then the output will be 199.

To solve this, we will follow these steps:

  • digits := a list with all digits in n
  • bound := null
  • for i in range size of digits - 1 down to 0, do
    • if digits[i] < digits[i - 1], then
      • bound := i
      • digits[i - 1] := digits[i - 1] - 1
    • if bound is not null, then
      • for i in range bound to size of digits, do
        • digits[i] := 9
  • join each digit in digits to form a number and return it

Let us see the following implementation to get better understanding:

Example Code

Live Demo

class Solution:
   def solve(self, n):
      digits = [int(x) for x in str(n)]
      bound = None
      for i in range(len(digits) - 1, 0, -1):
         if digits[i] < digits[i - 1]:
            bound = i
            digits[i - 1] -= 1
         if bound:
            for i in range(bound, len(digits)):
               digits[i] = 9
         return int("".join(map(str, digits)))

ob = Solution()
n = 221
print(ob.solve(n))

Input

221

Output

199
raja
Published on 25-Nov-2020 12:53:29
Advertisements