You are viewing a single comment's thread. Return to all comments →
def highestValuePalindrome(s, n, k): # Write your code here if n == 1: if k: return "9" else: return s mismatched = 0 mid = (len(s) // 2) idxs = set() final = [] for i in range(mid): if s[i] != s[n-(i+1)]: mismatched += 1 idxs.add(i) final.append(str(max(int(s[i]), int(s[n-(i+1)])))) else: final.append(s[i]) i += 1 if mismatched > k: return "-1" else: extra = k - mismatched i = 0 while extra: if final[i] != "9": if i in idxs: extra -= 1 final[i] = "9" else: if extra > 1: final[i] = "9" extra -= 2 i += 1 if i == len(final): break if len(s) % 2 == 0: return "".join(final) + "".join(final[::-1]) else: if extra: return "".join(final) + "9" + "".join(final[::-1]) else: return "".join(final) + s[mid] + "".join(final[::-1])
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 →