[LeetCode] Delivering Boxes from Storage to Ports

1687. 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​, weighti], and three integers portsCount, maxBoxes, and maxWeight.

  • ports​​i is the port where you need to deliver the ith box and weightsi is the weight of the ith 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
int boxDelivering(vector<vector<int>>& boxes, int portsCount, int b, int w) {
int n = boxes.size();
vector<int> dp(n + 1, 2*n+2);
dp[0]=0;
int trip = 0, r = 0, diffR = 0;
for(int l = 0; l < n; l++) {
while(r < n and b > 0 and w >= boxes[r][1]) {
b--;
w-=boxes[r][1];
if(r == 0 or boxes[r][0] != boxes[r-1][0]) {
diffR = r;
trip++;
}
r++;
}
dp[r] = min(dp[r], dp[l] + trip + 1);
dp[diffR] = min(dp[diffR], dp[l] + trip);
b++;
w+=boxes[l][1];
if(l != n - 1 and boxes[l][0] != boxes[l+1][0]) {
trip--;
}
}
return dp.back();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/19/PS/LeetCode/delivering-boxes-from-storage-to-ports/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.