Minimum Cost to Make Array Equalindromic Problem
Description
LeetCode Problem 2967.
You are given an integer array nums.
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 nums equal 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.
Constraints:
1 <= n <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Preprocessing + Sorting + Binary Search
Every palindrome up to 10^9 is formed by taking a number from 1 to 10^5 and mirroring it, either with the last digit repeated (even length) or dropped (odd length). Generate all of them once into a sorted array ps.
The total cost sum |nums[i] - x| is smallest at the median of nums, and it grows as x moves away from the median. So only the palindromes next to the median matter: binary search the median in ps and evaluate the cost for the palindrome found and its two neighbors, then take the minimum.
The time complexity is O(n log n) and the space complexity is O(M), where n is the length of nums and M is the number of palindromes in ps.
from bisect import bisect_left
ps = []
for i in range(1, 10**5 + 1):
s = str(i)
t1 = s[::-1]
t2 = s[:-1][::-1]
ps.append(int(s + t1))
ps.append(int(s + t2))
ps.sort()
class Solution:
def minimumCost(self, nums: List[int]) -> int:
def f(x: int) -> int:
return sum(abs(v - x) for v in nums)
nums.sort()
i = bisect_left(ps, nums[len(nums) // 2])
return min(f(ps[j]) for j in range(i - 1, i + 2) if 0 <= j < len(ps))