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,intk){char[]chars=s.ToCharArray();// calculate count of unbalanced pairs in the stringintm=0;inti1=0;intj1=s.Length-1;while(i1<j1){if(s[i1]!=s[j1])m++;i1++;j1--;}// it is not enough 'k' in advanceif(k<m)return"-1";inti2=0;intj2=s.Length-1;// we prefer both '9' if possiblewhile(i2<j2){if(CanSetBoth9Digits()){chars[i2]=chars[j2]='9';k-=2;if(s[i2]!=s[j2])m-=1;}elseif(s[i2]>s[j2]){chars[j2]=chars[i2];k--;m--;}elseif(s[i2]<s[j2]){chars[i2]=chars[j2];k--;m--;}i2++;j2--;}if(i2==j2&&k>0)chars[i2]='9';returnnewstring(chars);boolCanSetBoth9Digits(){if(s[i2]=='9'||s[j2]=='9')returnfalse;booldigitsEqual=s[i2]==s[j2];return(!digitsEqual&&k>m)||(digitsEqual&&k>m+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 →
Here is my C# solution: