LeetCode 2463: Minimum Total Distance Traveled Solution

Master LeetCode problem 2463 (Minimum Total Distance Traveled), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2463. Minimum Total Distance Traveled

Problem Explanation

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.

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2463 (Minimum Total Distance Traveled)?

This page provides optimized solutions for LeetCode problem 2463 (Minimum Total Distance Traveled) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2463 (Minimum Total Distance Traveled)?

The time complexity for LeetCode 2463 (Minimum Total Distance Traveled) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2463 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2463 in Java, C++, or Python.

Back to LeetCode Solutions