Delivering Boxes from Storage to Ports

You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry.

You are given an array boxes, where boxes[i] = [ports_i, weight_i], and three integers portsCount, maxBoxes, and maxWeight.

  • ports_i is the port where you need to deliver the i^th box and weight_i is the weight of the i^th box.
  • portsCount is the number of ports.
  • maxBoxes and maxWeight are the respective box and weight limits of the ship.

The boxes need to be delivered in the order they are given. The ship will follow these steps:

  • The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints.
  • For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered.
  • The ship then makes a return trip to storage to take more boxes from the queue.

The ship must end at storage after all the boxes have been delivered.

Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.

Example 1
Inputboxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3
Output4
The optimal strategy is to take all boxes, visit port 1, then port 2, then port 1 again, and return to storage for 4 trips.
Example 2
Inputboxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6
Output6
The optimal strategy uses three shipments costing 2 trips each: the first box, then the second through fourth boxes, then the fifth box, for a total of 6 trips.

Constraints

  • 1 <= boxes.length <= 10^5
  • 1 <= portsCount, maxBoxes, maxWeight <= 10^5
  • 1 <= ports_i <= portsCount
  • 1 <= weights_i <= maxWeight

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate