1146. Next-Fit Boxes

Easy1.5 points estimatedSimulationGreedyArray

A warehouse packs parcels into boxes in the order they arrive on a conveyor, and only one box is open at a time. Each parcel in weights is placed into the open box if the box's total load stays at most capacity. Otherwise the open box is sealed for good and a new box is opened for that parcel. The very first parcel opens the first box. Return the number of boxes used. Sealed boxes are never reopened, even if a later light parcel would have fitted into them.

1 <= weights.length <= 10^4 and 1 <= weights[i] <= capacity <= 10^6, so every parcel fits in an empty box. One pass with O(1) extra space is intended.

Example 1

Input:
weights = [4,5,3,2,6], capacity = 10
Output:
3
Explanation:

Box 1 holds 4 and 5, then 3 does not fit; box 2 holds 3 and 2, then 6 does not fit, so box 3 holds 6.

Example 2

Input:
weights = [6,6,6], capacity = 10
Output:
3
Explanation:

No two parcels fit together, so each gets its own box.

Example 3

Input:
weights = [1,2,3], capacity = 100
Output:
1
Explanation:

Everything fits in the first box.

Constraints

1 ≤ weights.length ≤ 104

1 ≤ weights[i] ≤ capacity ≤ 106

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…