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):sArr=list(s)half=(n>>1)+1count=k# check non-palindromeidxL,idxR=0,n-1whileidxL<=idxR:ifsArr[idxL]!=sArr[idxR]:# use the max value of themsArr[idxL]=sArr[idxR]=max(sArr[idxL],sArr[idxR])count-=1# if there are more than k invalid digits, return -1 ifcount<0:return'-1'idxL,idxR=idxL+1,idxR-1# repalce 9idxL,idxR=0,n-1whileidxL<=idxR:ifidxL==idxR:# if it is the middle one(odd length), try to set the digit to 9ifcount>0:sArr[idxL]='9'else:deduct=0ifsArr[idxL]<'9':# set the pair of digits to 9 if it is necessaryifsArr[idxL]!=s[idxL]orsArr[idxR]!=s[idxR]:# if this pair of digits are invalid, reduce by 1, # because the counter has already decrased by 1 beforededuct=1else:# otherwise, decrease the counter by 2deduct=2# if the counter is still greater or equals to 0, execute it if(count-deduct)>=0:sArr[idxL]=sArr[idxR]='9'count-=deductidxL,idxR=idxL+1,idxR-1return''.join(sArr)
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 →