LeetCode 1687: Delivering Boxes from Storage to Ports Solution

Master LeetCode problem 1687 (Delivering Boxes from Storage to Ports), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we can use a greedy approach. We will iterate through the boxes in order and simulate the process of loading boxes onto the ship and delivering them to the ports. We will keep track of the current number of boxes on the ship, the current total weight on the ship, the current port the ship is at, and the total trips made by the ship.

For each box, we will check if adding it to the ship will exceed the maximum box limit or weight limit. If it does, we will deliver the current boxes on the ship to the current port and update the ship's state accordingly. We will continue this process until all boxes are delivered.

The time complexity of this solution is O(n), where n is the number of boxes. The space complexity is O(1) as we are using constant extra space.

Solution Code

class Solution {
    public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {
        int trips = 0;
        int currBoxes = 0;
        int currWeight = 0;
        int currPort = 0;
        
        for (int i = 0; i < boxes.length; i++) {
            int[] box = boxes[i];
            int boxPort = box[0];
            int boxWeight = box[1];
            
            if (i > 0 && boxPort != boxes[i - 1][0]) {
                trips++;
            }
            
            if (currBoxes + 1 > maxBoxes || currWeight + boxWeight > maxWeight) {
                trips++;
                currBoxes = 0;
                currWeight = 0;
                i--;
                continue;
            }
            
            currBoxes++;
            currWeight += boxWeight;
            currPort = boxPort;
        }
        
        return trips + 1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1687 (Delivering Boxes from Storage to Ports)?

This page provides optimized solutions for LeetCode problem 1687 (Delivering Boxes from Storage to Ports) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1687 (Delivering Boxes from Storage to Ports)?

The time complexity for LeetCode 1687 (Delivering Boxes from Storage to Ports) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1687 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1687 in Java, C++, or Python.

Back to LeetCode Solutions