Delivering Boxes from Storage to Ports - Problem
You have the task of delivering boxes from storage to their ports using only one ship. The ship has limits on the number of boxes and total weight it can carry.
You are given an array boxes where boxes[i] = [portsi, weighti], and three integers portsCount, maxBoxes, and maxWeight.
portsiis the port where you need to deliver the ith boxweightsiis the weight of the ith boxportsCountis the number of portsmaxBoxesandmaxWeightare the ship's capacity limits
The boxes must be delivered in the given order. The ship follows these steps:
- Take boxes from the queue without violating
maxBoxesandmaxWeightconstraints - For each loaded box in order, make a trip to deliver it (if already at the correct port, no trip needed)
- Return to storage to take more boxes
The ship must end at storage after all deliveries. Return the minimum number of trips needed.
Input & Output
Example 1 — Basic Case
$
Input:
boxes = [[1,1],[4,6],[1,2],[2,7],[3,2]], portsCount = 3, maxBoxes = 4, maxWeight = 6
›
Output:
6
💡 Note:
Trip 1: Take boxes [1,1],[4,6] but weight exceeds. Take only [1,1], deliver to port 1, return. Trip 2: Take [4,6], deliver to port 4, return. Trip 3: Take [1,2],[2,7] but weight exceeds. Take [1,2], deliver to port 1, return. Trip 4: Take [2,7], deliver to port 2, return. Trip 5: Take [3,2], deliver to port 3. Total: 6 trips.
Example 2 — Efficient Grouping
$
Input:
boxes = [[1,2],[3,3],[1,1]], portsCount = 3, maxBoxes = 3, maxWeight = 6
›
Output:
4
💡 Note:
Trip 1: Take all boxes [1,2],[3,3],[1,1] (weight = 6, boxes = 3). Deliver to port 1, then port 3, then port 1 again. Total: 4 trips (1→3→1→storage).
Example 3 — Single Box Per Trip
$
Input:
boxes = [[1,4],[2,5]], portsCount = 2, maxBoxes = 1, maxWeight = 10
›
Output:
4
💡 Note:
Trip 1: Take [1,4], deliver to port 1, return. Trip 2: Take [2,5], deliver to port 2. Total: 4 trips.
Constraints
- 1 ≤ boxes.length ≤ 105
- 1 ≤ portsCount, boxes[i][0] ≤ 105
- 1 ≤ boxes[i][1] ≤ 105
- 1 ≤ maxBoxes, maxWeight ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Boxes with [port, weight], ship constraints maxBoxes, maxWeight
2
Process
Group consecutive boxes optimally, count unique ports per group
3
Output
Minimum total trips needed (2×ports per group, except last)
Key Takeaway
🎯 Key Insight: Use DP to optimally group consecutive boxes, minimizing total trips by balancing load sizes with unique port counts per trip.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code