Javascript - Nearest Palindromes
Code\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minimumCost = function (nums) {\n  const n = nums.length;\n  nums.sort((a, b) => a - b);\n
# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minimumCost = function (nums) {\n  const n = nums.length;\n  nums.sort((a, b) => a - b);\n\n  // median value\n  const midIdx = Math.floor(n / 2);\n  let median = nums[midIdx];\n  if (n % 2 === 0) {\n    median = Math.floor((nums[midIdx] + nums[midIdx - 1]) / 2);\n  }\n  const medianString = String(median);\n  const m = medianString.length;\n\n  // case 1: one digit less\n  const c1 = String(10 ** (m - 1) - 1);\n\n  // case 2: one digit more\n  const c2 = String(10 ** m + 1);\n\n  // case 3: mirror left\n  let c3 = medianString.split(\'\');\n  for (let i = 0; i < Math.floor(m / 2); i++) {\n    c3[m - 1 - i] = c3[i];\n  }\n  c3 = c3.join(\'\');\n\n  // case 4: mirorr left + 1\n  const c4 = helper(medianString, m, 1);\n\n  // case 5: mirror left - 1;\n  const c5 = helper(medianString, m, -1);\n\n  let ans = Infinity;\n  const palindromes = [c1, c2, c3, c4, c5];\n  for (const palindrome of palindromes) {\n    let cost = 0;\n    for (const num of nums) {\n      cost += Math.abs(+palindrome - num);\n    }\n    ans = Math.min(ans, cost);\n  }\n\n  return ans;\n};\n\nfunction helper(medianString, m, value) {\n  const substring = medianString.slice(0, Math.ceil(m / 2));\n  const first = +substring + value;\n  let second = String(first); // if even\n  if (m % 2 === 1) second = second.slice(0, second.length - 1);\n  second = second.split(\'\').reverse().join(\'\');\n\n  return `${first}${second}`;\n}\n\n```
['Sorting', 'JavaScript']