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.
Python 3 solution inspired by/adapting the simple C++ solution a few comments down:
# Write your code here
diff = [0]*n
temp = k
il = [int(x) for x in s]
#make a base palindrome first if possible
for i in range(len(il)//2 +1):
if il[i] != il[len(il)-1-i] and temp == 0:
return '-1'
if il[i] != il[len(il)-1-i]:
cmax = max( il[i], il[len(il)-1-i])
il[i] = cmax
il[len(il)-1-i] = cmax
temp -= 1
diff[i] = 1
#make all as many elements 9s as possible starting from the biggest digit
for i in range(len(il)//2 +1):
#if no more changes can be made return the completed string
if temp == 0:
return ''.join(map(str, il))
if diff[i] == 1 or i == len(il)-1-i:
if il[i] != 9:
il[i] = 9
il[len(il)-1-i] = 9
temp -= 1
elif diff[i] == 0 and temp >= 2:
if il[i] != 9:
il[i] = 9
il[len(il)-1-i] = 9
temp -= 2
return ''.join(map(str, il))
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 →
Python 3 solution inspired by/adapting the simple C++ solution a few comments down: