Sponsored
Sponsored
The Greedy Approach involves sorting both the robots and factories based on their positions. We try to assign each robot to the closest possible factory without exceeding the factory's limit, thus minimizing the travel distance one step at a time.
Time Complexity: O(n log n + m log m), where n is the number of robots and m is the number of factories due to the sorting step. The assignment step is O(n + m).
Space Complexity: O(1), not counting input space as we sort in-place.
1import java.util.Arrays;
2
3class Solution {
4 public static int minTotalDistance(int[] robots, int[][] factories) {
5 Arrays.sort(robots);
6 Arrays.sort(factories, (a, b) -> Integer.compare(a[0], b[0]));
7 int distance = 0;
8 int robIndex = 0, factIndex = 0;
9
10 while (robIndex < robots.length) {
11 if (factories[factIndex][1] != 0) {
12 distance += Math.abs(robots[robIndex] - factories[factIndex][0]);
13 factories[factIndex][1]--;
14 robIndex++;
15 } else {
16 factIndex++;
17 }
18 }
19
20 return distance;
21 }
22
23 public static void main(String[] args) {
24 int[] robots = {0, 4, 6};
25 int[][] factories = {{2, 2}, {6, 2}};
26 System.out.println("Minimum Total Distance: " + minTotalDistance(robots, factories));
27 }
28}
The Java solution leverages Java's Arrays library to sort the arrays and performs a similar greedy procedure to assign robots to the nearest valid factory, minimizing total travel distance.
A Dynamic Programming approach could involve maintaining a DP table where each entry dp[i][j] represents the minimum distance needed to repair the first i robots using the first j factories. This approach could find optimal assignments by considering various combinations and memoizing the results, though it might be more computationally intensive for larger datasets than the greedy approach.
Time Complexity: O(n * m * l), where l is the maximum capacity of a factory, due to nested loops.
Space Complexity: O(n * m), for storing the DP table.
1def min_total_distance_dp(robots, factories):
2 robots.sort()
3
In this Python solution, a DP table is constructed that tracks the minimum distance for repairing a certain number of robots using a given number of factories. By incrementally building up solutions for subproblems, it finds the optimal total travel distance.