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.
defhighestValuePalindrome(s,n,k):s=list(s)s=[int(ele)foreleins]modified_idxs=set()# create any palindromforleft_idxinrange(0,n// 2):right_idx=n-1-left_idxifs[left_idx]!=s[right_idx]:ifk>=1:# change one to greater valmax_val=max(s[left_idx],s[right_idx])s[left_idx]=max_vals[right_idx]=max_valk-=1modified_idxs.add(left_idx)else:# not palindrome and can't do any more changes so return -1return"-1"# here we know palindrome can be created, now let's max itforleft_idxinrange(0,n// 2):ifk<1:breakright_idx=n-1-left_idxifs[left_idx]==9ands[right_idx]==9:# can't do any bettercontinueifleft_idxinmodified_idxsandk>=1:# already modified, so we need just one change to change two numberss[left_idx]=9s[right_idx]=9k-=1elifk>=2:# not modified yet, we need to changes to change to 9ss[left_idx]=9s[right_idx]=9k-=2# handle middleifn%2==1andk>=1:middle_idx=n// 2s[middle_idx]=9return"".join([str(ele)foreleins])
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 →