HardNo. 1687
Delivering Boxes from Storage to Ports — LeetCode 1687 Python Solution
- Pattern
- Prefix Sum
- Topics
- Segment Tree, Queue, Array, Dynamic Programming, Prefix Sum, Monotonic Queue, Heap (Priority Queue)
- Reading time
- 3 min
- Source
- leetcode.com
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
# 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
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 1696 | Jump Game VI | Medium |
| 1425 | Constrained Subsequence Sum | Hard |
| 2407 | Longest Increasing Subsequence II | Hard |
| 2944 | Minimum Number of Coins for Fruits | Medium |
| 0918 | Maximum Sum Circular Subarray | Medium |
| 0673 | Number of Longest Increasing Subsequence | Medium |
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.