|
| 1 | +/** |
| 2 | + * 1687. Delivering Boxes from Storage to Ports |
| 3 | + * https://leetcode.com/problems/delivering-boxes-from-storage-to-ports/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You have the task of delivering some boxes from storage to their ports using only one ship. |
| 7 | + * However, this ship has a limit on the number of boxes and the total weight that it can carry. |
| 8 | + * |
| 9 | + * You are given an array boxes, where boxes[i] = [portsi, weighti], and three integers |
| 10 | + * portsCount, maxBoxes, and maxWeight. |
| 11 | + * - portsi is the port where you need to deliver the ith box and weightsi is the weight of |
| 12 | + * the ith box. |
| 13 | + * - portsCount is the number of ports. |
| 14 | + * - maxBoxes and maxWeight are the respective box and weight limits of the ship. |
| 15 | + * |
| 16 | + * The boxes need to be delivered in the order they are given. The ship will follow these steps: |
| 17 | + * - The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and |
| 18 | + * maxWeight constraints. |
| 19 | + * - For each loaded box in order, the ship will make a trip to the port the box needs to be |
| 20 | + * delivered to and deliver it. If the ship is already at the correct port, no trip is needed, |
| 21 | + * and the box can immediately be delivered. |
| 22 | + * - The ship then makes a return trip to storage to take more boxes from the queue. |
| 23 | + * |
| 24 | + * The ship must end at storage after all the boxes have been delivered. |
| 25 | + * |
| 26 | + * Return the minimum number of trips the ship needs to make to deliver all boxes to their |
| 27 | + * respective ports. |
| 28 | + */ |
| 29 | + |
| 30 | +/** |
| 31 | + * @param {number[][]} boxes |
| 32 | + * @param {number} portsCount |
| 33 | + * @param {number} maxBoxes |
| 34 | + * @param {number} maxWeight |
| 35 | + * @return {number} |
| 36 | + */ |
| 37 | +var boxDelivering = function(boxes, portsCount, maxBoxes, maxWeight) { |
| 38 | + const n = boxes.length; |
| 39 | + const minTrips = new Array(n + 1).fill(0); |
| 40 | + let start = 0; |
| 41 | + let portChanges = 0; |
| 42 | + |
| 43 | + for (let end = 0; end < n; end++) { |
| 44 | + maxBoxes--; |
| 45 | + maxWeight -= boxes[end][1]; |
| 46 | + if (end > 0 && boxes[end][0] !== boxes[end - 1][0]) portChanges++; |
| 47 | + |
| 48 | + while (maxBoxes < 0 || maxWeight < 0 |
| 49 | + || (start < end && minTrips[start + 1] === minTrips[start])) { |
| 50 | + maxBoxes++; |
| 51 | + maxWeight += boxes[start++][1]; |
| 52 | + if (start > 0 && boxes[start][0] !== boxes[start - 1][0]) portChanges--; |
| 53 | + } |
| 54 | + |
| 55 | + minTrips[end + 1] = portChanges + 2 + minTrips[start]; |
| 56 | + } |
| 57 | + |
| 58 | + return minTrips[n]; |
| 59 | +}; |
0 commit comments