Highest Value Palindrome

  • + 0 comments

    My version

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    #
    # Complete the 'highestValuePalindrome' function below.
    #
    # The function is expected to return a STRING.
    # The function accepts following parameters:
    #  1. STRING s
    #  2. INTEGER n
    #  3. INTEGER k
    #
    _marks=[]
    def _create_palindrom(s):
        count=0
        s=list(s)
        for i in range(len(s)//2):
            #check string
            if (s[i]<s[len(s)-i-1]):
                count+=1
                s[i]=s[len(s)-i-1]
                _marks.append(i)
            elif s[i]>s[len(s)-i-1]:
                s[len(s)-i-1]=s[i]
                count+=1
                _marks.append(i)
        return s, count
                
        
    def _maximize_palindrome(s, k, count):
       if k>0 and len(s)==1:
           s[0]='9'
           return
       for i in range(len(s)//2):
           #change the current symbol
           if k>1 and s[i]<'9' and i not in _marks:
               s[i]='9'
               s[len(s)-i-1]='9'
               k-=2
           elif count>0 and s[i]<'9' and i in _marks:    
                s[i]='9'
                s[len(s)-i-1]='9'
                if count>1:
                   count-=2
                else:
                    count-=1
                    k-=1
       #change the middle         
       if k==1 and len(s)%2>0 and count>=0:
             s[len(s)//2]='9'
               
               
    
    def highestValuePalindrome(s, n, k):
        res, count=_create_palindrom(s)
        if count>k:
            return '-1'
        if count<k:
            _maximize_palindrome(res, k-count, count) 
        return ''.join(res)
        
        # Write your code here
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        first_multiple_input = input().rstrip().split()
    
        n = int(first_multiple_input[0])
    
        k = int(first_multiple_input[1])
    
        s = input()
    
        result = highestValuePalindrome(s, n, k)
    
        fptr.write(result + '\n')
    
        fptr.close()