Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
portsi is the port where you need to deliver the ith box and weightsi is the weight of the ith box.portsCount is the number of ports.maxBoxes and maxWeight are the respective box and weight limits of the ship.The boxes need to be delivered in the order they are given. The ship will follow these steps:
boxes queue, not violating the maxBoxes and maxWeight constraints.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: - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips. 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 2, 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: - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips. - The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips. - The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6.
Constraints:
1 <= boxes.length <= 1051 <= portsCount, maxBoxes, maxWeight <= 1051 <= portsi <= portsCount1 <= weightsi <= maxWeightProblem summary: 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. portsi is the port where you need to deliver the ith box and weightsi is the weight of the ith box. portsCount is the number of ports. maxBoxes and maxWeight are the respective box and weight limits of the ship. The boxes need to be delivered in the order they are given. The ship will follow these steps: The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints. For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Segment Tree · Monotonic Queue
[[1,1],[2,1],[1,1]] 2 3 3
[[1,2],[3,3],[3,1],[3,1],[2,4]] 3 3 6
[[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]] 3 6 7
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1687: Delivering Boxes from Storage to Ports
class Solution {
public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {
int n = boxes.length;
long[] ws = new long[n + 1];
int[] cs = new int[n];
for (int i = 0; i < n; ++i) {
int p = boxes[i][0], w = boxes[i][1];
ws[i + 1] = ws[i] + w;
if (i < n - 1) {
cs[i + 1] = cs[i] + (p != boxes[i + 1][0] ? 1 : 0);
}
}
int[] f = new int[n + 1];
Deque<Integer> q = new ArrayDeque<>();
q.offer(0);
for (int i = 1; i <= n; ++i) {
while (!q.isEmpty()
&& (i - q.peekFirst() > maxBoxes || ws[i] - ws[q.peekFirst()] > maxWeight)) {
q.pollFirst();
}
if (!q.isEmpty()) {
f[i] = cs[i - 1] + f[q.peekFirst()] - cs[q.peekFirst()] + 2;
}
if (i < n) {
while (!q.isEmpty() && f[q.peekLast()] - cs[q.peekLast()] >= f[i] - cs[i]) {
q.pollLast();
}
q.offer(i);
}
}
return f[n];
}
}
// Accepted solution for LeetCode #1687: Delivering Boxes from Storage to Ports
func boxDelivering(boxes [][]int, portsCount int, maxBoxes int, maxWeight int) int {
n := len(boxes)
ws := make([]int, n+1)
cs := make([]int, n)
for i, box := range boxes {
p, w := box[0], box[1]
ws[i+1] = ws[i] + w
if i < n-1 {
t := 0
if p != boxes[i+1][0] {
t++
}
cs[i+1] = cs[i] + t
}
}
f := make([]int, n+1)
q := []int{0}
for i := 1; i <= n; i++ {
for len(q) > 0 && (i-q[0] > maxBoxes || ws[i]-ws[q[0]] > maxWeight) {
q = q[1:]
}
if len(q) > 0 {
f[i] = cs[i-1] + f[q[0]] - cs[q[0]] + 2
}
if i < n {
for len(q) > 0 && f[q[len(q)-1]]-cs[q[len(q)-1]] >= f[i]-cs[i] {
q = q[:len(q)-1]
}
q = append(q, i)
}
}
return f[n]
}
# Accepted solution for LeetCode #1687: Delivering Boxes from Storage to Ports
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 = [0] * (n + 1)
q = deque([0])
for i in range(1, n + 1):
while q and (i - q[0] > maxBoxes or ws[i] - ws[q[0]] > maxWeight):
q.popleft()
if q:
f[i] = cs[i - 1] + f[q[0]] - cs[q[0]] + 2
if i < n:
while q and f[q[-1]] - cs[q[-1]] >= f[i] - cs[i]:
q.pop()
q.append(i)
return f[n]
// Accepted solution for LeetCode #1687: Delivering Boxes from Storage to Ports
/**
* [1687] Delivering Boxes from Storage to Ports
*
* 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.
*
* portsi is the port where you need to deliver the i^th box and weightsi is the weight of the i^th box.
* portsCount is the number of ports.
* maxBoxes and maxWeight are the respective box and weight limits of the ship.
*
* The boxes need to be delivered in the order they are given. The ship will follow these steps:
*
* The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints.
* For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered.
* The ship then makes a return trip to storage to take more boxes from the queue.
*
* 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:
* - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.
* 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 2, 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:
* - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.
* - The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.
* - The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.
* So the total number of trips is 2 + 2 + 2 = 6.
*
*
* Constraints:
*
* 1 <= boxes.length <= 10^5
* 1 <= portsCount, maxBoxes, maxWeight <= 10^5
* 1 <= portsi <= portsCount
* 1 <= weightsi <= maxWeight
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/delivering-boxes-from-storage-to-ports/
// discuss: https://leetcode.com/problems/delivering-boxes-from-storage-to-ports/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/delivering-boxes-from-storage-to-ports/solutions/3189455/just-a-runnable-solution/
pub fn box_delivering(
boxes: Vec<Vec<i32>>,
ports_count: i32,
max_boxes: i32,
max_weight: i32,
) -> i32 {
let n = boxes.len();
let (mut need, mut j, mut lastj) = (0, 0, 0);
let (mut max_boxes, mut max_weight) = (max_boxes, max_weight);
let mut dp = vec![200000; n + 1];
dp[0] = 0;
for i in 0..n {
while j < n && max_boxes > 0 && max_weight >= boxes[j][1] {
max_boxes -= 1;
max_weight -= boxes[j][1];
if j == 0 || boxes[j][0] != boxes[j - 1][0] {
lastj = j;
need += 1;
}
j += 1;
}
dp[j] = dp[j].min(dp[i] + need + 1);
dp[lastj] = dp[lastj].min(dp[i] + need);
max_boxes += 1;
max_weight += boxes[i][1];
if i == n - 1 || boxes[i][0] != boxes[i + 1][0] {
need -= 1;
}
}
dp[n]
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1687_example_1() {
let boxes = vec![vec![1, 1], vec![2, 1], vec![1, 1]];
let ports_count = 2;
let max_boxes = 3;
let max_weight = 3;
let result = 4;
assert_eq!(
Solution::box_delivering(boxes, ports_count, max_boxes, max_weight),
result
);
}
#[test]
fn test_1687_example_2() {
let boxes = vec![vec![1, 2], vec![3, 3], vec![3, 1], vec![3, 1], vec![2, 4]];
let ports_count = 3;
let max_boxes = 3;
let max_weight = 6;
let result = 6;
assert_eq!(
Solution::box_delivering(boxes, ports_count, max_boxes, max_weight),
result
);
}
#[test]
fn test_1687_example_3() {
let boxes = vec![
vec![1, 4],
vec![1, 2],
vec![2, 1],
vec![2, 1],
vec![3, 2],
vec![3, 4],
];
let ports_count = 3;
let max_boxes = 6;
let max_weight = 7;
let result = 6;
assert_eq!(
Solution::box_delivering(boxes, ports_count, max_boxes, max_weight),
result
);
}
}
// Accepted solution for LeetCode #1687: Delivering Boxes from Storage to Ports
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1687: Delivering Boxes from Storage to Ports
// class Solution {
// public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {
// int n = boxes.length;
// long[] ws = new long[n + 1];
// int[] cs = new int[n];
// for (int i = 0; i < n; ++i) {
// int p = boxes[i][0], w = boxes[i][1];
// ws[i + 1] = ws[i] + w;
// if (i < n - 1) {
// cs[i + 1] = cs[i] + (p != boxes[i + 1][0] ? 1 : 0);
// }
// }
// int[] f = new int[n + 1];
// Deque<Integer> q = new ArrayDeque<>();
// q.offer(0);
// for (int i = 1; i <= n; ++i) {
// while (!q.isEmpty()
// && (i - q.peekFirst() > maxBoxes || ws[i] - ws[q.peekFirst()] > maxWeight)) {
// q.pollFirst();
// }
// if (!q.isEmpty()) {
// f[i] = cs[i - 1] + f[q.peekFirst()] - cs[q.peekFirst()] + 2;
// }
// if (i < n) {
// while (!q.isEmpty() && f[q.peekLast()] - cs[q.peekLast()] >= f[i] - cs[i]) {
// q.pollLast();
// }
// q.offer(i);
// }
// }
// return f[n];
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.