Approach
Sorting and greedy selection
For Minimum Cost to Make Array Equalindromic, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 33 lines of C++ from the credited upstream file 2967.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 long long minimumCost(vector<int>& nums) {4 ranges::sort(nums);5 const int median = nums[nums.size() / 2];6 const int nextPalindrome = getPalindrome(median, 1);7 const int prevPalindrome = getPalindrome(median, -1);8 return min(cost(nums, nextPalindrome), cost(nums, prevPalindrome));9 }10 11 private:12 13 long cost(const vector<int>& nums, int palindrome) {14 return accumulate(nums.begin(), nums.end(), 0L,15 [palindrome](long acc, int num) {16 return acc + abs(palindrome - num);17 });18 }19 20 21 int getPalindrome(int num, int delta) {22 while (!isPalindrome(num))23 num += delta;24 return num;25 }26 27 bool isPalindrome(int num) {28 const string original = to_string(num);29 const string reversed = {original.rbegin(), original.rend()};30 return original == reversed;31 }32};33