Minimum Cost to Make Array Equalindromic - Problem
Transform Array to Palindromic Equality!
You're given an integer array
The Rules:
• You can change any element
• Each change costs
• The final target must be a palindromic number (reads same forwards and backwards)
• Target must be less than 109
Examples of palindromes: 1, 11, 121, 1331, 12321
Non-palindromes: 10, 123, 1234
Find the minimum total cost to make all array elements equal to some palindromic number!
You're given an integer array
nums and your mission is to make all elements equal to the same palindromic number with minimum cost.The Rules:
• You can change any element
nums[i] to any positive integer x• Each change costs
|nums[i] - x| (absolute difference)• The final target must be a palindromic number (reads same forwards and backwards)
• Target must be less than 109
Examples of palindromes: 1, 11, 121, 1331, 12321
Non-palindromes: 10, 123, 1234
Find the minimum total cost to make all array elements equal to some palindromic number!
Input & Output
example_1.py — Basic Case
$
Input:
[1,2,3,4,5]
›
Output:
6
💡 Note:
We can change all elements to palindromic number 3. Cost = |1-3| + |2-3| + |3-3| + |4-3| + |5-3| = 2 + 1 + 0 + 1 + 2 = 6. This is the minimum possible cost.
example_2.py — Single Element
$
Input:
[10,12,13,14,15]
›
Output:
11
💡 Note:
The optimal palindromic target is 11. Cost = |10-11| + |12-11| + |13-11| + |14-11| + |15-11| = 1 + 1 + 2 + 3 + 4 = 11.
example_3.py — Large Numbers
$
Input:
[100,110,120]
›
Output:
21
💡 Note:
The optimal palindromic target is 111. Cost = |100-111| + |110-111| + |120-111| = 11 + 1 + 9 = 21. Other palindromes like 101 or 121 would give higher costs.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
- Target palindrome must be less than 109
- All palindromic numbers from 1 to 9 are valid single-digit targets
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code