Ctrl K

Robots Collecting Coins

Hard
Robots stand and coins lie on a line: robots[i] is the position of the i-th robot and coins[j] is the position of the j-th coin. Several robots and coins may share a point. In one second a robot moves 1 step left or right; all robots move at the same time and independently. A robot picks up a coin instantly as soon as it is at the coin's point, and it can collect any number of coins. Return the fewest seconds in which the robots can collect every coin.
Example 1
robots=[2, 8], coins=[0, 5, 9] → 5

The first robot goes left to 0 (2 seconds). The second robot goes right to 9 first (1 second), then back to 5 (4 more), 5 seconds in total. Letting the first robot take 5 as well would cost it 2 + 5 = 7. The answer is 5.

Example 2
robots=[4, 4, 10], coins=[4, 10] → 0

Every coin already lies under a robot, so nobody has to move.

Example 3
robots=[0], coins=[3, 7] → 7

The only robot drives right and picks up both coins on the way: 7 seconds.

Constraints
  • 1 ≤ len(robots), len(coins) ≤ 2·10⁴
  • 0 ≤ robots[i], coins[j] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsK-th Smallest Pair Gap HardBusy Server Pairs HardFlowerbed Beauty on a Budget HardTriples Under a Limit MediumValues in Both Lists Easy
loading Python…
Input
robots=[2, 8], coins=[0, 5, 9]
Expected
5

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