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.
voidlargest_pal(string&s,intn,int&k,vector<bool>&changed){intl=0,h=n-1;while(l<=h&&k>0){if(l==h){//middleif(k>0&&s[l]!='9'){s[l]='9';k--;}}else{if(s[l]!='9'){if(changed[l]||changed[h]){// Only 1 change needed to upgrade both to '9'if(k>=1){s[l]=s[h]='9';k--;}}elseif(k>=2){// 2 changes needed to upgrade both to '9's[l]=s[h]='9';k-=2;}}}l++;h--;}}stringhighestValuePalindrome(strings,intn,intk){vector<bool>changed(n,false);// int val = check_palindrome(s,n,k,changed);intl=0,h=n-1;//First pass: Make the string a palindrome with minimal changes, record changed positionswhile(l<=h){if(s[l]!=s[h]){if(k==0)return"-1";if(s[l]>s[h])s[h]=s[l];elses[l]=s[h];k--;changed[l]=changed[h]=true;}l++;h--;}//Second pass: Maximize the palindrome by upgrading pairs to '9'// if(n%2 == 1 && k==1){// s[n/2] = '9';// return s;// }largest_pal(s,n,k,changed);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 →