Skip to main content
Back to problems
#2463
Hard Algorithms

Minimum total distance traveled

Array Dynamic Programming Sorting
58.8% acceptance
Feb 25, 2026
964
33
There are some robots and factories on the X-axis. You are given an integer a rray robot where robot[i] is the position of the ith robot. You are also given a 2D integer array factory where factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory and that the jth factory can repair at most limitj robots. * The positions of each robot are unique. The positions of each factory are als o 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 d irection 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. Yo ur 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 All robots move at the same speed. If two robots move in the same direction, they will never collide. If two robots move in opposite directions and they meet at some point, they d o not collide. They cross each other. * If a robot passes by a factory that reached its limits, it crosses it as if i t does not exist. * If the robot moved from a position x to a position y, the distance it moved i s |y - x|. *

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_total_distance(mut robot: Vec<i32>, mut factory: Vec<Vec<i32>>) -> i64 {
    robot.sort();
    factory.sort_by_key(|f| f[0]);
    // Expand factory positions
    let mut pos: Vec<i64> = Vec::new();
    for f in &factory {
      for _ in 0..f[1] { pos.push(f[0] as i64); }
    }
    let r = robot.len();
    let s = pos.len();
    let inf = i64::MAX / 2;
    // dp[i][j] = min cost to assign first i robots using first j slots
    let mut dp = vec![vec![inf; s + 1]; r + 1];
    for j in 0..=s { dp[0][j] = 0; }
    for i in 1..=r {
      for j in 1..=s {
        dp[i][j] = dp[i][j - 1]; // don't use slot j for robot i
        if dp[i - 1][j - 1] < inf {
          let cost = dp[i - 1][j - 1] + (robot[i - 1] as i64 - pos[j - 1]).abs();
          dp[i][j] = dp[i][j].min(cost);
        }
      }
    }
    dp[r][s]
  }
}