[Leetcode] 1432. Max Difference You Can Get From Changing an Integer

whitehousechef·2025년 6월 16일

https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer/description/

initial

a minor change from the previous https://velog.io/@whitehousechef/Leetcode-2566.-Maximum-Difference-by-Remapping-a-Digit
but we cant have leading 0s this time.

So if the first digit is not a 1, then we can just replace that digit with 1. But if first digit is 1, we have to look for the next digit that isnt 1 or 0 (not 0 cuz theres no point substituting 0 with 0 to make value lower). Once we find that digit we replace that digit with 1.

sol

class Solution:
    def maxDiff(self, num: int) -> int:
        s = str(num)
        
        # Find first non-9 digit for max, first non-0 digit for min
        max_digit = next((d for d in s if d != '9'), '9')
        
        max_val = int(s.replace(max_digit, '9'))
        min_val=None
        if s[0]!='1':
            min_val=int(s.replace(s[0],'1'))
        else:
            min_digit = next((d for d in s if d != '1' and d!='0'), None)
            if min_digit:
                min_val=int(s.replace(min_digit,'0'))
            else:
                min_val=num
        return max_val - min_val                

complexity

n time
n space

0개의 댓글