2463. Minimum Total Distance Traveled #771
-
Topics: There are some robots and factories on the X-axis. You are given an integer array The positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially. All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving. At any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots. Return the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired. Note that
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
We can use dynamic programming with sorted
Let's implement this solution in PHP: 2463. Minimum Total Distance Traveled <?php
/**
* @param Integer[] $robot
* @param Integer[][] $factory
* @return Integer
*/
function minimumTotalDistance($robot, $factory) {
sort($robot);
usort($factory, function($a, $b) {
return $a[0] - $b[0];
});
$n = count($robot);
$m = count($factory);
$dp = array_fill(0, $n + 1, array_fill(0, $m + 1, PHP_INT_MAX));
$dp[0][0] = 0;
for ($j = 1; $j <= $m; $j++) {
$pos = $factory[$j - 1][0];
$limit = $factory[$j - 1][1];
for ($i = 0; $i <= $n; $i++) {
$dp[$i][$j] = $dp[$i][$j - 1];
$sumDist = 0;
for ($k = 1; $k <= min($limit, $i); $k++) {
$sumDist += abs($robot[$i - $k] - $pos);
$dp[$i][$j] = min($dp[$i][$j], $dp[$i - $k][$j - 1] + $sumDist);
}
}
}
return $dp[$n][$m];
}
// Test cases
$robot = [0, 4, 6];
$factory = [[2, 2], [6, 2]];
echo minimumTotalDistance($robot, $factory); // Output: 4
$robot = [1, -1];
$factory = [[-2, 1], [2, 1]];
echo minimumTotalDistance($robot, $factory); // Output: 2
?> Explanation:
Complexity
This solution efficiently calculates the minimum travel distance for all robots to be repaired within their factory limits. |
Beta Was this translation helpful? Give feedback.
We can use dynamic programming with sorted
robot
andfactory
arrays. The idea is to minimize the distance each robot must travel to be repaired by a factory, respecting each factory’s repair capacity. Here’s a step-by-step breakdown of the approach:Sort the
robot
andfactory
arrays by position. Sorting helps in minimizing the travel distance as we can assign nearby robots to nearby factories.Dynamic Programming Approach: We define a 2D DP table
dp[i][j]
where:i
represents the firsti
robots.j
represents the firstj
factories.dp[i][j]
stores the minimum total distance for repairing thesei
robots using thesej
factories.State Transition: