Approach
Breadth-first search
For Minimum Sum of Squared Difference, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 57 lines of Java from the credited upstream file 2333.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
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 minSumSquareDiff(int[] nums1, int[] nums2, int k1, int k2) {3 int[] diff = getDiff(nums1, nums2);4 int k = k1 + k2;5 if (Arrays.stream(diff).asLongStream().sum() <= k)6 return 0;7 8 Map<Integer, Integer> count = new HashMap<>();9 10 Queue<Pair<Integer, Integer>> maxHeap =11 new PriorityQueue<>(Comparator.comparing(Pair::getKey, Comparator.reverseOrder()));12 13 for (final int d : diff)14 if (d != 0)15 count.merge(d, 1, Integer::sum);16 17 for (Map.Entry<Integer, Integer> entry : count.entrySet())18 maxHeap.offer(new Pair<>(entry.getKey(), entry.getValue()));19 20 while (k > 0) {21 Pair<Integer, Integer> pair = maxHeap.poll();22 final int maxNum = pair.getKey();23 final int maxNumFreq = pair.getValue();24 25 final int numDecreased = Math.min(k, maxNumFreq);26 k -= numDecreased;27 if (maxNumFreq > numDecreased)28 maxHeap.offer(new Pair<>(maxNum, maxNumFreq - numDecreased));29 if (!maxHeap.isEmpty() && maxHeap.peek().getKey() + 1 == maxNum) {30 Pair<Integer, Integer> secondNode = maxHeap.poll();31 final int secondMaxNum = secondNode.getKey();32 final int secondMaxNumFreq = secondNode.getValue();33 maxHeap.offer(new Pair<>(secondMaxNum, secondMaxNumFreq + numDecreased));34 } else if (maxNum > 1) {35 maxHeap.offer(new Pair<>(maxNum - 1, numDecreased));36 }37 }38 39 long ans = 0;40 while (!maxHeap.isEmpty()) {41 Pair<Integer, Integer> pair = maxHeap.poll();42 final int num = pair.getKey();43 final int freq = pair.getValue();44 ans += (long) num * num * freq;45 }46 47 return ans;48 }49 50 private int[] getDiff(int[] nums1, int[] nums2) {51 int[] diff = new int[nums1.length];52 for (int i = 0; i < nums1.length; ++i)53 diff[i] = Math.abs(nums1[i] - nums2[i]);54 return diff;55 }56}57