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.
Java 8 solution.
Set added to save the changed pairs. so we dount get charged twice for the same number change.
publicstaticStringhighestValuePalindrome(Strings,intn,intk){intright=n/2;intleft=(n%2==0)?(n-1)/2:n/2;char[]c=s.toCharArray();// Tracking change indices.Set<Integer>changes=newHashSet<>();// Working out from the middle to generate the a Palindromes while(left>=0&&right<c.length&&k>=0){if(c[left]!=c[right]){// Found a none mathing pair, set to the max of either pair.c[left]=(char)Math.max(c[left],c[right]);c[right]=c[left];changes.add(left);--k;}--left;++right;}// Working in form the endswhile(k>0&&left<right){++left;--right;if(c[left]!='9'){if(changes.contains(left))// Add back the original change to the change count.++k;if(left==right){// Handle special case.c[left]='9';--k;}elseif(k>=2){c[left]='9';c[right]='9';k-=2;}}}return(k>=0)?newString(c):"-1";}
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 8 solution. Set added to save the changed pairs. so we dount get charged twice for the same number change.