2463. Minimum Total Distance Traveled

Explanation

To minimize the total distance traveled by all the robots, we can follow the steps:

  1. Sort the robots' positions in ascending order.
  2. For each factory, calculate the distance between it and the robots before it and after it.
  3. Repair the robots based on the distances from the factory.
  4. Calculate the total minimum distance traveled by all robots.

Time complexity: O(nlogn) where n is the number of robots. Space complexity: O(n) for storing the sorted robots' positions.

class Solution {
    public int minTotalDistance(int[] robot, int[][] factory) {
        Arrays.sort(robot);
        int n = robot.length;
        int totalDistance = 0;

        for (int[] fac : factory) {
            int pos = fac[0];
            int limit = fac[1];
            List<Integer> left = new ArrayList<>();
            List<Integer> right = new ArrayList<>();

            for (int r : robot) {
                if (r < pos) {
                    left.add(pos - r);
                } else if (r > pos) {
                    right.add(r - pos);
                }
            }

            Collections.sort(left);
            Collections.sort(right);

            int repaired = 0;
            for (int l : left) {
                if (repaired == limit) break;
                totalDistance += l;
                repaired++;
            }

            for (int r : right) {
                if (repaired == limit) break;
                totalDistance += r;
                repaired++;
            }
        }

        return totalDistance;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.