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.
My C++ solution with no additional memory space requirements
stringhighestValuePalindrome(strings,intn,intk){if(s.size()==0)returnstring("-1");if((size_t)k>=s.size())returnstring(s.size(),'9');inttotaldiffs=std::inner_product(s.begin(),s.begin()+s.size()/2,s.rbegin(),0,std::plus<int>(),std::not_equal_to<char>());if(totaldiffs>k)returnstring("-1");autoit_left=s.begin();autoit_right=prev(s.end());// left hand half of stringwhile(k>0){if(*it_left!=*it_right){if(k-totaldiffs>=1&&*it_left!='9'&&*it_right!='9'){// extra budget for one extra change*it_left=*it_right='9';k-=2;}else{*it_left=*it_right=max(*it_left,*it_right);--k;}--totaldiffs;}elseif(it_left!=it_right){//same digits but possibility to do some optimisationif(*it_left!='9'&&*it_right!='9'&&k-totaldiffs>1){*it_left=*it_right='9';k-=2;}}else{// middle digit*it_left='9';--k;}++it_left;--it_right;if(it_left>it_right)// break if we've processed all lettersbreak;}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 C++ solution with no additional memory space requirements