Ctrl K

Broken Robots on a Line

Hard
Broken robots and repair shops sit on a number line. The array robots holds the robots' coordinates, and shops[j] = [position, capacity] means a shop stands at position and can repair at most capacity robots. All robot coordinates are distinct, and so are all shop coordinates; a robot may start at the same point as a shop. You choose a direction for every robot, left or right, and it keeps driving that way. When a robot reaches a shop that still has room, the robot is repaired and stops. Robots drive straight through full shops, and they never get in each other's way. Return the smallest total distance driven by all robots. It is guaranteed that every robot can be repaired.
Example 1
robots=[1, 8], shops=[[3, 1], [7, 2]] → 3

The robot at 1 heads right to the shop at 3 (distance 2), and the robot at 8 heads left to the shop at 7 (distance 1). Total 3.

Example 2
robots=[0, 1, 2], shops=[[1, 2], [10, 3]] → 9

The shop at 1 takes only two robots: the ones at 0 and 1 (distance 1 + 0). The robot at 2 has to travel to 10, another 8. Total 9.

Constraints
  • 1 ≤ robots.length, shops.length ≤ 100
  • shops[j].length = 2
  • -10⁹ ≤ robots[i], position ≤ 10⁹
  • 0 ≤ capacity ≤ robots.length
  • Every robot can be repaired
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBoxes Inside Boxes HardStrict Climb From Spare Parts HardBest-Paying Set of Gigs HardLongest Downhill Route HardBiggest Number Divisible by Three Hard
loading Python…
Input
robots=[1, 8], shops=[[3, 1], [7, 2]]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.