Greedy Algorithms - Monotone Increasing Digits
Examine the following code snippet intended to find the largest monotone increasing digits number ≤
n. What is the subtle bug causing incorrect results on some inputs?def monotone_increasing_buggy(n):
digits = list(map(int, str(n)))
for i in range(1, len(digits)):
if digits[i] < digits[i-1]:
digits[i-1] -= 1
digits[i:] = [9] * (len(digits) - i)
return int(''.join(map(str, digits)))