We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#!/bin/python3importmathimportosimportrandomimportreimportsys## 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=0s=list(s)foriinrange(len(s)//2):#check stringif(s[i]<s[len(s)-i-1]):count+=1s[i]=s[len(s)-i-1]_marks.append(i)elifs[i]>s[len(s)-i-1]:s[len(s)-i-1]=s[i]count+=1_marks.append(i)returns,countdef_maximize_palindrome(s,k,count):ifk>0andlen(s)==1:s[0]='9'returnforiinrange(len(s)//2):#change the current symbolifk>1ands[i]<'9'andinotin_marks:s[i]='9's[len(s)-i-1]='9'k-=2elifcount>0ands[i]<'9'andiin_marks:s[i]='9's[len(s)-i-1]='9'ifcount>1:count-=2else:count-=1k-=1#change the middle ifk==1andlen(s)%2>0andcount>=0:s[len(s)//2]='9'defhighestValuePalindrome(s,n,k):res,count=_create_palindrom(s)ifcount>k:return'-1'ifcount<k:_maximize_palindrome(res,k-count,count)return''.join(res)# Write your code hereif__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()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Highest Value Palindrome
You are viewing a single comment's thread. Return to all comments →
My version