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.
defhighestValuePalindrome(s,n,k):# Convert the string to a mutable lists=list(s)# Step 1: Identify mismatched mirrored pairsmismatches=[]foriinrange(n// 2):ifs[i]!=s[n-i-1]:mismatches.append((i,n-i-1))# Step 2: Check if we have enough changes to fix all mismatchesiflen(mismatches)>k:return"-1"#Notenoughchangestomakeitapalindrome# Step 3: Fix mismatched mirrored pairsfori,jinmismatches:# Use the larger of the two digits to fix the mismatchs[i]=s[j]=max(s[i],s[j])k-=1#Countthisasonechange# Step 4: Maximize the palindrome using remaining changesforiinrange(n// 2):ifk<=0:break# If the current pair is not already '9', we can try to maximize itifs[i]!='9':# If this pair was previously fixed, it costs 1 changeif(i,n-i-1)inmismatches:s[i]=s[n-i-1]='9'k-=1# If this pair was already a match, it costs 2 changeselifk>=2:s[i]=s[n-i-1]='9'k-=2# If the string has an odd length, we can change the middle characterifn%2==1andk>0:s[n// 2] = '9'# Return the resulting palindromereturn''.join(s)
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 →