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.
importcollectionsdefhighestValuePalindrome(s,n,k):ifn==1:#Easilysolvableifn=1ifk>=1:return"9"else:returns#Get a string of the pure completed palindrome, along with an array of extra changes needed for both numbers to become "9"half=int(n//2)string=""extra_steps=collections.deque()foriinrange(half):left,right=s[i],s[n-1-i]change=0ifleft!=right:#Fixedneededifnotmatchingk-=1ifk<0:#Noneedtocontinueifimpossiblebreak#If neither are "9", then need one extra change to become "9"ifleft!="9"andright!="9":change=1#If matching and not equal to "9", two extra changes are needed to become "9"elifleft!="9":change=2string+=max(left,right)#Addthehighestvalueifk-change<0:#Can'tchangeto"9"ifnotenoughmovesareavailablechange=0extra_steps.append(change)ifk<0:#Failedifk<0return"-1"steps=0#Alsotheindexhigh_string=""forxinextra_steps:ifk-x>=0andx>0:#Nochangeifnotenoughattempsortherearenochangeshigh_string+="9"k-=xelse:high_string+=string[steps]steps+=1ifn%2==1:#Checkifthereisamiddledigitifk>0:#Canchangeto"9"ifthereisstillchangespossiblemiddle="9"else:#Otherwisetheoriginalmiddlemiddle=s[half]else:#Thereisnomiddlemiddle=""returnhigh_string+middle+high_string[::-1]
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 →
Python 3