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.
functionhighestValuePalindrome(s:string,n:number,k:number):string{constreplace=(s:string,i:number,c:string):string=>{returns.substring(0,i)+c+s.substring(i+1)}// 1. make [s] palidrome (required [k*] number of times), mark [i] that need to changes// - using larger value to replace, saving [k] in 2. stepletcircles=[]for(leti=0;i<Math.floor(n/2);i++){letj=n-i-1if(s[i]==s[j])continueif(s[i]>s[j])s=replace(s,j,s[i])if(s[i]<s[j])s=replace(s,i,s[j])k--circles.push(i)// no more [k] left, it can't be palidromeif(k<0)return'-1'}// 2. with remaining [k], replacement to increasing number value// - with [i] that marked only need changes 1 orelse 2// - with [s] is odd, changes the middle number if still have [k]for(leti=0;i<Math.floor(n/2);i++){letj=n-i-1if(s[i]!='9'){letk_=circles.includes(i)?1:2if(k>=k_){s=replace(s,i,'9')s=replace(s,j,'9')k-=k_}}}if(n%2==1&&k>0)s=replace(s,Math.floor(n/2),'9')// 3. return the final palidrome [s]returns}
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 answer with Typescript, simple