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){if(k>=n){varchars=Enumerable.Repeat('9',n).ToArray();returnnewstring(chars);}if(n==1&&k>0)return"9";varInvRequiredIndexes=MinChangesMakingPalindrome(s);varsetInvRequiredIndexes=InvRequiredIndexes.ToHashSet();varminChangesRequired=InvRequiredIndexes.Count;if(minChangesRequired>k)return"-1";vartheChars=s.ToCharArray();if(minChangesRequired==k){foreach(variinInvRequiredIndexes){if(theChars[i]>theChars[n-i-1])theChars[n-i-1]=theChars[i];elsetheChars[i]=theChars[n-i-1];}returnnewstring(theChars);}// k is > minChangesRequiredvaradditionalChangesAvailable=k-minChangesRequired;while(additionalChangesAvailable>0){for(vari=0;i<n/2&&additionalChangesAvailable>0;i++){if(setInvRequiredIndexes.Contains(i))// just 1 additional change needed{if(theChars[i]!='9'&&theChars[n-i-1]!='9')additionalChangesAvailable--;theChars[i]=theChars[n-i-1]='9';setInvRequiredIndexes.Remove(i);}elseif(theChars[i]!='9'&&additionalChangesAvailable>=2){theChars[i]=theChars[n-i-1]='9';additionalChangesAvailable-=2;}}break;}// Done with the additional changes. Now cary out the mandatory changes if any leftvarlstInvRequiredIndexes=setInvRequiredIndexes.ToList();for(vari=0;i<lstInvRequiredIndexes.Count;i++){varind=lstInvRequiredIndexes[i];if(additionalChangesAvailable>0){theChars[n-ind-1]=theChars[ind]='9';additionalChangesAvailable--;}elseif(theChars[ind]<theChars[n-ind-1])theChars[ind]=theChars[n-ind-1];elsetheChars[n-ind-1]=theChars[ind];}if(n%2!=0&&additionalChangesAvailable>0)theChars[n/2]='9';returnnewstring(theChars);}publicstaticList<int>MinChangesMakingPalindrome(strings){varlen=s.Length;varhalfLen=len/2;varinvIndexes=newList<int>{};for(vari=0;i<halfLen;i++){if(s[i]!=s[len-i-1])invIndexes.Add(i);}returninvIndexes;}
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 →
In C#: