Approach
Sorting and greedy selection
For Minimum Total Distance Traveled, 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
- 26 lines of Java from the credited upstream file 2463.java.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks 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 minimumTotalDistance(List<Integer> robot, int[][] factory) {3 Collections.sort(robot);4 Arrays.sort(factory, Comparator.comparingInt(a -> a[0]));5 long[][][] mem = new long[robot.size()][factory.length][robot.size()];6 return minimumTotalDistance(robot, factory, 0, 0, 0, mem);7 }8 9 private long minimumTotalDistance(List<Integer> robot, int[][] factory, int i, int j, int k,10 long[][][] mem) {11 if (i == robot.size())12 return 0;13 if (j == factory.length)14 return Long.MAX_VALUE;15 if (mem[i][j][k] > 0)16 return mem[i][j][k];17 final long skipFactory = minimumTotalDistance(robot, factory, i, j + 1, 0, mem);18 final int position = factory[j][0];19 final int limit = factory[j][1];20 final long useFactory = limit > k ? minimumTotalDistance(robot, factory, i + 1, j, k + 1, mem) +21 Math.abs(robot.get(i) - position)22 : Long.MAX_VALUE / 2;23 return mem[i][j][k] = Math.min(skipFactory, useFactory);24 }25}26