In one operation, you may choose an index i and either increment or decrement nums[i] by 1.
Return the minimum number of operations required to make every element in numsequal to the same positive palindromic integer.
Example 1:
Input: nums = [1,2,3,4,5]
Output: 6
Explanation: Increment nums[0] twice and nums[1] once, then decrement nums[3] once and nums[4] twice. After 6 operations, nums becomes [3,3,3,3,3], and 3 is a positive palindromic integer.
It can be shown that this is the minimum number of operations required.
Example 2:
Input: nums = [10,12,13,14,15]
Output: 11
Explanation: Increment nums[0] once, then decrement nums[1], nums[2], nums[3], and nums[4] by 1, 2, 3, and 4, respectively. After 11 operations, nums becomes [11,11,11,11,11], and 11 is a positive palindromic integer.
It can be shown that this is the minimum number of operations required.
Example 3:
Input: nums = [22,33,22,33,22]
Output: 22
Explanation: Decrement nums[1] and nums[3] by 11 each. After 22 operations, nums becomes [22,22,22,22,22], and 22 is a positive palindromic integer.
It can be shown that this is the minimum number of operations required.
All values become one palindrome; the \(L_1\) cost is minimized near the median. Palindromes are generated by mirroring halves in \([1,10^5]\) and stored in sorted \(ps\).
Sort \(\textit{nums}\), binary-search \(ps\) around the median, and evaluate a few neighbors. \(n \le 10^5\), so the target is not enumerated exhaustively.
The range of palindrome numbers in the problem is \([1, 10^9]\). Due to the symmetry of palindrome numbers, we can enumerate in the range of \([1, 10^5]\), then reverse and concatenate them to get all palindrome numbers. Note that if it is an odd-length palindrome number, we need to remove the last digit before reversing. The array of palindrome numbers obtained by preprocessing is denoted as \(ps\). We sort the array \(ps\).
Next, we sort the array \(\textit{nums}\) and take the median \(x\) of \(\textit{nums}\). We only need to find a number in the palindrome array \(ps\) that is closest to \(x\) through binary search, and then calculate the cost of \(\textit{nums}\) becoming this number to get the answer.
The time complexity is \(O(n \log n)\), and the space complexity is \(O(M)\), where \(n\) is the length of the array \(\textit{nums}\), and \(M\) is the length of the palindrome array \(ps\).