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
- 28 lines of Java from the credited upstream file 2967.java.
- 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 long minimumCost(int[] nums) {3 Arrays.sort(nums);4 final int median = nums[nums.length / 2];5 final int nextPalindrome = getPalindrome(median, 1);6 final int prevPalindrome = getPalindrome(median, -1);7 return Math.min(cost(nums, nextPalindrome), cost(nums, prevPalindrome));8 }9 10 11 private long cost(int[] nums, int palindrome) {12 return Arrays.stream(nums).mapToLong(num -> Math.abs(palindrome - num)).sum();13 }14 15 16 private int getPalindrome(int num, int delta) {17 while (!isPalindrome(num))18 num += delta;19 return num;20 }21 22 private boolean isPalindrome(int num) {23 final String original = Integer.toString(num);24 final String reversed = new StringBuilder(original).reverse().toString();25 return original.equals(reversed);26 }27}28