Concise Python code with explanation

  • 0

    The idea is you scan from left to right and try to satisfy the condition s[i] <= s[i+1]
    If that condition is not satisfied to try picking the next lower largest number...

    Keep doing this until its good.

    class Solution:
        def monotoneIncreasingDigits(self, N):
            s = [int(c) for c in str(N)]
            while True:
                substract = 1
                for i in range(len(s) - 1):
                    if s[i] > s[i+1]:
                        s[i], s[i+1] = s[i] - substract, 9
                        substract = 0
                if substract: break
            return int("".join([str(c) for c in s]))

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.