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.
stringmakePalindrome(strings,intn,intk,boolodd,stringfirst,stringsecond,intdiff){stringresult;//rest will be number of extra changes we can do in palindromeintrest=k-diff;//this map will show if the index is included in making normal palindromeunordered_map<int,bool>included;for(inti=0;i<n/2;i++){if(first[i]!=second[n/2-i-1]){if(first[i]>second[n/2-i-1])second[n/2-1-i]=first[i];elsefirst[i]=second[n/2-1-i];included[i]=true;//include the index if it is changed}}for(inti=0;i<n/2;i++){//if the index is not included then rest will be deducted by 2if(first[i]!='9'&&!included[i]){rest-=2;if(rest<0){rest+=2;continue;}//setting the changed indexfirst[i]=second[n/2-i-1]='9';}//else by 1elseif(first[i]!='9'&&included[i]){rest--;if(rest<0){rest++;continue;}first[i]=second[n/2-i-1]='9';}}if(odd){if(rest)s[n/2]='9';}if(odd)result=first+s[n/2]+second;elseresult=first+second;returnresult;}// Complete the highestValuePalindrome function below.stringhighestValuePalindrome(strings,intn,intk){if(n==1){if(k>0)return"9";elseif(k==0)returns;elsereturn"-1";}stringfirst,second,result;intlen=n/2;boolodd;if(n%2==0)odd=false;elseodd=true;first.assign(s,0,n/2);if(odd)second.assign(s,n/2+1,n);elsesecond.assign(s,n/2,n);intdifferent=0;for(inti=0;i<n/2;i++){if(first[i]!=second[n/2-i-1]){different++;}}if(k<different)return"-1";elseresult=makePalindrome(s,n,k,odd,first,second,different);returnresult;}
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 →
what am i doing wrong here