Delivering Boxes from Storage to Ports — LeetCode 1687 Python Solution

HardSegment TreeQueueArrayDynamic ProgrammingPrefix SumMonotonic QueueHeap (Priority Queue)
Problem
#1687
Pattern
Prefix Sum
Reading time
3 min

The problem

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.

Example

Input
boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3
Output
4
Explanation
The optimal strategy is as follows:

Python solution

Python
# 33/39
class Solution:
    def boxDelivering(
        self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int
    ) -> int:
        n = len(boxes)
        ws = list(accumulate((box[1] for box in boxes), initial=0))
        c = [int(a != b) for a, b in pairwise(box[0] for box in boxes)]
        cs = list(accumulate(c, initial=0))
        f = [inf] * (n + 1)
        f[0] = 0
        for i in range(1, n + 1):
            for j in range(max(0, i - maxBoxes), i):
                if ws[i] - ws[j] <= maxWeight:
                    f[i] = min(f[i], f[j] + cs[i - 1] - cs[j] + 2)
        return f[n]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1687. Delivering Boxes from Storage to Ports is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1687. Delivering Boxes from Storage to Ports?
LeetCode 1687. Delivering Boxes from Storage to Ports is rated Hard on LeetCode.
What is the time complexity of LeetCode 1687. Delivering Boxes from Storage to Ports?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1687. Delivering Boxes from Storage to Ports?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1687. Delivering Boxes from Storage to Ports cover?
LeetCode 1687. Delivering Boxes from Storage to Ports is tagged Segment Tree, Queue, Array, Dynamic Programming, Prefix Sum, Monotonic Queue and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview