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.
funhighestValuePalindrome(s:String,n:Int,k:Int):String{// Write your code herevarchangesLeft=k// list that keeps positions at which we changed a number// usage will be visible latervalappliedChangesAt=mutableListOf<Int>()varnumber=s.toCharArray()// pointersvarl=0varr=s.length-1// makes a palindrom, as long as the ponters do not cross each otherwhile(l<=r){// perform replacements when there are any changes left// and the numbers are not equal (will not create a palindrome)if(changesLeft>0&&number[l]!=number[r]){// check which size has a bigger value, and replace the smaller one with itif(number[l]>number[r]){number[r]=number[l]// note where the change happen, so that we can // perform an additional (cheat) change laterappliedChangesAt.add(r)}else{number[l]=number[r]appliedChangesAt.add(l)}// decrement the amount of available changes, // as for sure we changed something abovechangesLeft--}// if the numbers are not the same after supposed change,// this means that we run out of possible changes, and cannot make it a palindromeif(number[l]!=number[r])return"-1"// update pointersl++r--}//reset pointersl=0r=s.length-1// perform changes as long as it is possiblewhile(changesLeft>0&&l<=r){// it is a case when there is odd length of the number, // and we want to replace the center number with the 9if(l==r&&changesLeft==1){number[l]='9'number[r]='9'}// we want to replace only when the number is != 9, otherwise it is a waste of changeif(number[l]!='9'){valwereChangesAppliedToOneOfThem=linappliedChangesAt||rinappliedChangesAt// we can perform at least 2 changes, thats why we check if one of // the items was already changes, in that instance, // we want to reduce only by 1, instead of 2if(changesLeft>1&&!wereChangesAppliedToOneOfThem){number[l]='9'number[r]='9'changesLeft-=2}elseif(wereChangesAppliedToOneOfThem){number[l]='9'number[r]='9'changesLeft--}}// update pointersl++r--}returnString(number)}
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 →
kotlin solution with explanation