Ctrl K

Ferry Runs From the Depot

Hard
A ferry carries crates from a depot to ports. The crates wait in the queue crates, where crates[i] = [port, weight]; ports are numbered 1 to ports. On a single run the ferry can take at most max_crates crates with a total weight of at most max_load. Each run goes like this: - the ferry loads some of the **next crates in the queue** (their order cannot change); - it delivers them strictly in loading order: if the next crate goes to a different port, the ferry sails there, which is one leg; if it goes to the port where the ferry already is, it is unloaded with no leg; - it sails back to the depot, one more leg. Once every crate is delivered, the ferry must be back at the depot. Return the smallest total number of legs.
Example 1
crates=[[2, 3], [2, 1], [1, 2], [2, 2]], ports=2, max_crates=4, max_load=5 → 5

Run one takes crates 0 and 1 (weight 4) to port 2 and back: 2 legs. Run two takes crates 2 and 3 (weight 4) to port 1, then port 2, then back: 3 legs. Total 5. The first three crates together would weigh 6, over the limit of 5.

Example 2
crates=[[1, 1], [1, 1], [1, 1]], ports=3, max_crates=2, max_load=10 → 4

Every crate goes to port 1, but the ferry holds only two at a time: two runs of 2 legs each, 4 in total.

Constraints
  • 1 ≤ len(crates) ≤ 10⁵
  • 1 ≤ ports, max_crates, max_load ≤ 10⁵
  • 1 ≤ crate port ≤ ports
  • 1 ≤ crate weight ≤ max_load
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsA Dark Gap Between Street Lamps HardShortest Stretch Reaching a Total HardMaximum Sum With Short Hops HardLongest Affordable Run of Machines HardRising Chain With Small Steps Hard
loading Python…
Input
crates=[[2, 3], [2, 1], [1, 2], [2, 2]], ports=2, max_crates=4, max_load=5
Expected
5

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