Highest Value Palindrome

  • + 0 comments

    symmetry, maxize, mid

    def highestValuePalindrome(s, n, k):
        # Write your code here
        s=list(s)
        deduct=[0 for i in range(n)]
        # 1. make sure symmetric...deduction=[]
        curr=k
        mid=n//2
        for i in range(mid):
            if s[i] != s[n-1-i]: # need altering
                curr -= 1
                if curr<0:
                    return "-1"
                deduct[i]=1
                if s[i]>s[n-1-i]:
                    s[n-1-i]=s[i]
                elif s[i]<s[n-1-i]:
                    s[i]=s[n-1-i]
                # print(curr,s)
        # 2. maxize...
        for i in range(mid):
            if s[i] != '9' and curr>=2-deduct[i]: # maxize and afford
                s[i] = '9'
                s[n-1-i]='9'
                curr -= (2-deduct[i])
                # print(curr,s)
                if curr==0:
                    break
        # 3. special case mid
        if curr>0 and n % 2==1:
            s[mid]='9'
        return "".join(s)