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.
publicstaticStringhighestValuePalindrome(Strings,intn,intk){// Write your code hereintmax=n-1;intmin=0;char[]arr=s.toCharArray();boolean[]changeArr=newboolean[n];while(max>=min){if(arr[max]!=arr[min]){charmaxChar=(char)Math.max(arr[max],arr[min]);arr[max]=arr[min]=maxChar;k--;if(k<0)return"-1";changeArr[max]=changeArr[min]=true;}max--;min++;}// if still steps left maximize the string// Already changed in step 1, changing to '9' costs 1 more// Not changed before, changing both costs 2max=n-1;min=0;while(k>0&&min<max){// Check if either of the digits at the current positions is not already '9'// If so, we can consider upgrading them to '9' to increase the valueif(arr[min]!='9'||arr[max]!='9'){if(changeArr[max]||changeArr[min]){//if Already changed in step 1, changing to '9' costs 1 morearr[max]=arr[min]='9';k--;}else{if(k>=2)// if k =1 or zero we can't make 2 changes{arr[max]=arr[min]='9';k=k-2;}}}max--;min++;}//change middel in odd in lengthif(k>0){if(n%2!=0){intmid=n/2;arr[mid]='9';k--;}}returnnewString(arr);}
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 →
JAVA