983. Robots to Repair Shops
Robots stand on a long straight road at the positions in robots. Each entry of factories is [position, limit]: a repair depot at that position that can service at most limit robots. Robots and depots may share positions, and several of them may sit at the same spot.
Every robot must be sent to exactly one depot, walking along the road, so its cost is the absolute difference of the positions. A depot never services more than its limit. The depots together have enough capacity for all robots. Return the minimum possible total walking distance.
Example 1
- Input:
- robots = [-4,3,10], factories = [[0,2],[12,1]]
- Output:
- 9
- Explanation:
Robots at -4 and 3 go to the depot at 0 (costs 4 and 3), and the robot at 10 goes to the depot at 12 (cost 2): total 9.
Example 2
- Input:
- robots = [5,5,20,21], factories = [[5,1],[18,3],[100,4]]
- Output:
- 18
- Explanation:
One robot at 5 uses the depot at 5 (cost 0); the other robot at 5 and the robots at 20 and 21 use the depot at 18 (13 + 2 + 3), total 18.
Constraints
- 1 ≤ robots.length, factories.length ≤ 2000
- -109 ≤ robots[i], factories[j][0] ≤ 109
- 0 ≤ factories[j][1] ≤ robots.length
- The sum of all limits is at least robots.length
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 800 msC++ 200 msJava 400 msJavaScript 400 msTypeScript 400 ms
Expected complexity
- Time
- O(R * F)
- Space
- O(R)