Similar Problems

Similar Problems not available

Delivering Boxes From Storage To Ports - Leetcode Solution

Companies:

LeetCode:  Delivering Boxes From Storage To Ports Leetcode Solution

Difficulty: Hard

Topics: dynamic-programming prefix-sum heap-priority-queue array  

Problem:

There are n boxes in a warehouse where boxes[i] is the weight of the i-th box. Your task is to load these boxes onto a truck and deliver them to a port to be shipped.

The truck has a maximum capacity of maxBoxes boxes and can carry a maximum weight of maxWeight. Your task is to deliver as many boxes as possible to the port without exceeding the truck's capacity or weight limit.

You need to write a function that will determine the maximum number of boxes you can deliver to the port.

The function signature is:

int maxBoxes(int[] boxes, int maxBoxes, int maxWeight)

Input:

  • boxes: an array of n integers representing the weight of the boxes (1 <= n <= 10^5, 1 <= boxes[i] <= 1000)
  • maxBoxes: an integer representing the maximum number of boxes that the truck can carry (1 <= maxBoxes <= n)
  • maxWeight: an integer representing the maximum weight that the truck can carry (1 <= maxWeight <= 10^5)

Output:

  • The maximum number of boxes that can be delivered to port.

Example:

Input: boxes = [1,2,3], maxBoxes = 3, maxWeight = 3 Output: 3

Input: boxes = [1,2,3], maxBoxes = 3, maxWeight = 6 Output: 3

Input: boxes = [1,2,3], maxBoxes = 2, maxWeight = 1 Output: 0

Solution:

To solve the problem, we need to sort the array of boxes in descending order of weight. This way, we can start loading the boxes with the maximum weight first and thus maximize the number of boxes we can load onto the truck.

We then iterate over the sorted array of boxes, keeping track of the number of boxes and weight we have loaded onto the truck so far. We continue to load boxes onto the truck as long as we have not exceeded the maximum capacity or weight limit of the truck.

Once we have loaded as many boxes as possible onto the truck, we return the number of boxes loaded.

Here is the code implementation:

def maxBoxes(boxes, maxBoxes, maxWeight):
    boxes.sort(reverse=True)
    num_boxes, weight = 0, 0
    for box in boxes:
        if num_boxes < maxBoxes and weight + box <= maxWeight:
            num_boxes += 1
            weight += box
        else:
            break
    return num_boxes

This implementation has a time complexity of O(nlogn) due to the sorting of the array and a space complexity of O(1) as we are using constant extra space to store the number of boxes and weight loaded onto the truck so far.

Delivering Boxes From Storage To Ports Solution Code

1