Highest Value Palindrome

  • + 0 comments
        if n == 1 and k > 0:
            return '9'
        count = sum([1 for i in range(n//2) if s[i] != s[-i-1]])
        if k < count:
            return '-1'
        ex = k-count
        s = list(s)
        for i in range(n//2):
            if s[i] == s[-i-1] != '9' and ex > 1:
                s[i] = s[-i-1] = '9'
                ex -=2
            elif s[i] != s[-i-1]:
                if s[i] == '9' or s[-i-1] == '9':
                    s[i] = s[-i-1] = '9'
                else:
                    if ex > 0:
                        s[i] = s[-i - 1] = '9'
                        ex -= 1
                    else:
                        s[i] = s[-i - 1] = max(s[i], s[-i - 1])
        if ex > 0 and n % 2 == 1:
            s[n//2] = '9'
        return ''.join(s)