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.
def highestValuePalindrome`(s, n, k)
arr = s.split('')
while (k > 0 && n > 1)
firstIndex = 0
lastIndex = n - 1
while (firstIndex < lastIndex)
if (arr[firstIndex] != arr[lastIndex])
if (arr[firstIndex] < arr[lastIndex])
arr[firstIndex] = arr[lastIndex]
else
arr[lastIndex] = arr[firstIndex]
end
k -= 1
end
firstIndex += 1
lastIndex -= 1
end
n -= 2
end
if (k > 0)
midIndex = n / 2
if (n.odd? && arr[midIndex] != '9' && k >= 1)
arr[midIndex] = '9'
k -= 1
end
firstIndex = 0
lastIndex = n - 1
while (firstIndex < lastIndex && k >= 2)
if (arr[firstIndex] != '9')
arr[firstIndex] = '9'
arr[lastIndex] =
Highest Value Palindrome
You are viewing a single comment's thread. Return to all comments →
All test cases passed
def highestValuePalindrome`(s, n, k) arr = s.split('') while (k > 0 && n > 1) firstIndex = 0 lastIndex = n - 1 while (firstIndex < lastIndex) if (arr[firstIndex] != arr[lastIndex]) if (arr[firstIndex] < arr[lastIndex]) arr[firstIndex] = arr[lastIndex] else arr[lastIndex] = arr[firstIndex] end k -= 1 end firstIndex += 1 lastIndex -= 1 end n -= 2 end if (k > 0) midIndex = n / 2 if (n.odd? && arr[midIndex] != '9' && k >= 1) arr[midIndex] = '9' k -= 1 end firstIndex = 0 lastIndex = n - 1 while (firstIndex < lastIndex && k >= 2) if (arr[firstIndex] != '9') arr[firstIndex] = '9' arr[lastIndex] =