LeetCode-in-Java

1687. Delivering Boxes from Storage to Ports

Hard

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] = [portsi, weighti], and three integers portsCount, maxBoxes, and maxWeight.

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

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:

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 3, 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:

So the total number of trips is 2 + 2 + 2 = 6.

Constraints:

Solution

@SuppressWarnings("java:S1172")
public class Solution {
    public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {
        int t = 2;
        int weight = 0;
        int n = boxes.length;
        int[] dp = new int[n + 1];
        dp[0] = 0;
        int left = 0;
        for (int right = 0; right < boxes.length; right++) {
            weight += boxes[right][1];
            if (right > 0 && boxes[right][0] != boxes[right - 1][0]) {
                t++;
            }
            // checking if weight, boxes are less than or equal to max contraint
            while (weight > maxWeight
                    || right - left >= maxBoxes
                    || (left < right && dp[left] == dp[left + 1])) {
                weight -= boxes[left][1];
                if (boxes[left][0] != boxes[left + 1][0]) {
                    t--;
                }
                left++;
            }
            dp[right + 1] = dp[left] + t;
        }
        return dp[n];
    }
}