Time to Cross a Bridge - Problem
There are k workers who want to move n boxes from the right (old) warehouse to the left (new) warehouse. You are given the two integers n and k, and a 2D integer array time of size k x 4 where time[i] = [righti, picki, lefti, puti].
The warehouses are separated by a river and connected by a bridge. Initially, all k workers are waiting on the left side of the bridge. To move the boxes, the ith worker can do the following:
- Cross the bridge to the right side in
rightiminutes. - Pick a box from the right warehouse in
pickiminutes. - Cross the bridge to the left side in
leftiminutes. - Put the box into the left warehouse in
putiminutes.
The ith worker is less efficient than the jth worker if either condition is met:
lefti + righti > leftj + rightjlefti + righti == leftj + rightjandi > j
The following rules regulate the movement of the workers through the bridge:
- Only one worker can use the bridge at a time.
- When the bridge is unused, prioritize the least efficient worker (who have picked up the box) on the right side to cross. If not, prioritize the least efficient worker on the left side to cross.
- If enough workers have already been dispatched from the left side to pick up all the remaining boxes, no more workers will be sent from the left side.
Return the elapsed minutes at which the last box reaches the left side of the bridge.
Input & Output
Example 1 — Basic Bridge Crossing
$
Input:
n = 1, k = 3, time = [[1,1,2,1],[1,3,3,1],[1,2,1,1]]
›
Output:
6
💡 Note:
Worker 2 (efficiency=2) is least efficient, so crosses first. Takes 1 min to cross right + 2 min to pick + 1 min to cross left + 1 min to put = 5 min total. But worker 2 finishes putting at time 6.
Example 2 — Multiple Workers
$
Input:
n = 3, k = 2, time = [[1,9,1,8],[10,10,10,10]]
›
Output:
50
💡 Note:
Worker 1 has efficiency 20 (less efficient than worker 0's efficiency 2), so worker 1 goes first for each box. Each round takes about 41 minutes for worker 1.
Example 3 — Single Worker
$
Input:
n = 2, k = 1, time = [[5,2,3,1]]
›
Output:
21
💡 Note:
Only one worker available. First box: 5+2+3+1=11 min. Second box: starts at time 11, finishes at 11+5+2+3+1=22. But since putting starts at time 21, answer is 21.
Constraints
- 1 ≤ n, k ≤ 104
- time.length == k
- time[i].length == 4
- 1 ≤ righti, picki, lefti, puti ≤ 1000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code