Delivering Boxes from Storage to Ports Problem
Description
LeetCode Problem 1687.
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_iis the port where you need to deliver thei^thbox andweights_iis the weight of thei^thbox.portsCountis the number of ports.maxBoxesandmaxWeightare 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
boxesqueue, not violating themaxBoxesandmaxWeightconstraints. - 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:
Input: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3
Output: 4
Explanation: The optimal strategy is as follows:
- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.
So the total number of trips is 4.
Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).
Example 2:
Input: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6
Output: 6
Explanation: The optimal strategy is as follows:
- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.
- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.
- The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips.
So the total number of trips is 2 + 2 + 2 = 6.
Example 3:
Input: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7
Output: 6
Explanation: The optimal strategy is as follows:
- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.
- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.
- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.
So the total number of trips is 2 + 2 + 2 = 6.
Constraints:
1 <= boxes.length <= 10^51 <= portsCount, maxBoxes, maxWeight <= 10^51 <= ports_i <= portsCount1 <= weights_i <= maxWeight
Solution
Approach: Dynamic Programming + Monotonic Queue
Let f[i] be the fewest trips needed to deliver the first i boxes, so the answer is f[n].
Boxes must go in order, so each trip carries a contiguous block of boxes. If the last trip carries boxes j + 1 .. i, then f[i] = f[j] + cost(j + 1, i), where the block must hold at most maxBoxes boxes and weigh at most maxWeight.
The cost of one trip is 2 (leaving the storage and coming back) plus the number of times the port changes between neighbouring boxes in the block. For example, boxes for ports 4, 4, 5 take storage -> 4 -> 5 -> storage, which is 3 trips. With prefix sums:
ws[i]is the total weight of the firstiboxes;cs[i]counts the port changes among the firsti + 1boxes.
Then the cost of the block j + 1 .. i is cs[i - 1] - cs[j] + 2, and
f[i] = cs[i - 1] + 2 + min(f[j] - cs[j]) over valid j.
Trying every j is O(n^2), which is too slow for n up to 10^5. The valid j form a sliding window (it only moves right as i grows), so keep a monotonic queue of candidates with increasing f[j] - cs[j]:
- pop from the front while the front is too far back (
i - j > maxBoxes) or too heavy (ws[i] - ws[j] > maxWeight); - the front then gives the minimum, so compute
f[i]; - pop from the back while
f[back] - cs[back] >= f[i] - cs[i], then pushi.
Complexity: O(n) time and O(n) space, where n is the number of boxes.
from collections import deque
from itertools import accumulate
class Solution:
def boxDelivering(
self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int
) -> int:
n = len(boxes)
ws = list(accumulate((box[1] for box in boxes), initial=0))
c = [int(boxes[i][0] != boxes[i + 1][0]) for i in range(n - 1)]
cs = list(accumulate(c, initial=0))
f = [0] * (n + 1)
q = deque([0])
for i in range(1, n + 1):
while q and (i - q[0] > maxBoxes or ws[i] - ws[q[0]] > maxWeight):
q.popleft()
if q:
f[i] = cs[i - 1] + f[q[0]] - cs[q[0]] + 2
if i < n:
while q and f[q[-1]] - cs[q[-1]] >= f[i] - cs[i]:
q.pop()
q.append(i)
return f[n]