Skip to content

Instantly share code, notes, and snippets.

@ricardo1512
Last active February 27, 2024 21:31
Show Gist options
  • Save ricardo1512/d4dcb46126670cc66333bb586a136adf to your computer and use it in GitHub Desktop.
Save ricardo1512/d4dcb46126670cc66333bb586a136adf to your computer and use it in GitHub Desktop.
# https://www.hackerrank.com/challenges/richie-rich/problem
def highestValuePalindrome(LisT, n, changes):
number = list(LisT)
oddString = True if n % 2 != 0 else False
# Main loop starts in the middle:
left = n // 2 - 1
right = left + 1 if not oddString else left + 2
# Inspecting, for remaining changes, how many are needed to '9' changes:
nines = [0 for _ in range(left + 1)]
for i in range(left + 1):
if number[i] != "9" and number[-1 - i] != "9":
nines[i] = 2 if i == 0 else 2 + nines[i - 1]
elif number[i] != "9" or number[-1 - i] != "9":
nines[i] = 1 if i == 0 else 1 + nines[i - 1]
else:
nines[i] = nines[i - 1]
# Function to change to '9':
def allToNine(List, lft, changes):
for i in range(lft + 1):
if List[i] != "9" and List[-1 - i] != "9":
List[i] = List[-1 - i] = "9"
changes -= 2
elif List[i] != "9" or List[-1 - i] != "9":
List[i] = List[-1 - i] = "9"
changes -= 1
return changes
# Main loop:
while changes >= 0 and left >= 0:
if nines[left] <= changes:
changes = allToNine(number, left, changes)
break
# If elements are different, use a change to set them to the maximum:
if number[left] != number[right]:
if changes <= 0:
return "-1" # The lenght of string may not be altered!
else:
number[left] = number[right] = max(number[left], number[right])
changes -= 1
left -= 1
right += 1
# For strings with odd length, if any change remains, change the center:
if changes >= 1 and oddString:
number[n // 2] = "9"
return "".join(number)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment