Highest Value Palindrome

  • + 0 comments

    Python 3 solution inspired by/adapting the simple C++ solution a few comments down:

        # Write your code here
    diff = [0]*n
    temp = k
    il = [int(x) for x in s]
    
    #make a base palindrome first if possible
    for i in range(len(il)//2 +1):
        if il[i] != il[len(il)-1-i] and temp == 0:
            return '-1'
        if il[i] != il[len(il)-1-i]:
            cmax = max( il[i], il[len(il)-1-i])
            il[i] = cmax
            il[len(il)-1-i] = cmax
            temp -= 1
            diff[i] = 1
    
    
    #make all as many elements 9s as possible starting from the biggest digit
    for i in range(len(il)//2 +1):
    
        #if no more changes can be made return the completed string
        if temp == 0:
            return ''.join(map(str, il))
    
        if diff[i] == 1 or i == len(il)-1-i:
            if il[i] != 9:
                il[i] = 9
                il[len(il)-1-i] = 9
                temp -= 1
        elif diff[i] == 0 and temp >= 2:
            if il[i] != 9:
                il[i] = 9
                il[len(il)-1-i] = 9
                temp -= 2
    
    return ''.join(map(str, il))