Partition Items Into Bins With Limited Capacity
Dynamic ProgrammingAuto-graded · 17 test casesLast updated
Tests the classic bounded knapsack variant where you must determine the minimum number of identical bins needed so each bin's total weight stays within a capacity, using DP to check feasibility.
Partition Items Into Bins With Limited Capacity
You are managing a warehouse that ships items in identical boxes. Each box can hold a total weight of at most capacity. You are given a list of item weights and must pack all items using as few boxes as possible.
However, there is an additional constraint: each box may hold at most max_per_bin items (by count), regardless of total weight.
Write a function that returns the minimum number of boxes needed to ship all items while satisfying both constraints, or -1 if it is impossible (e.g., a single item exceeds capacity).
Task
Given:
weights: a list of positive integers representing item weightscapacity: an integer, the maximum total weight per boxmax_per_bin: an integer, the maximum number of items per box
Return the minimum number of boxes required, or -1 if any item cannot fit in a single box (i.e., its weight exceeds capacity).
Strategy
Use dynamic programming. Define the state as the minimum number of boxes needed to pack exactly a prefix of items given that the last (current) box has already accumulated a certain weight and item count. Sorting items in decreasing order of weight is a useful preprocessing step.
Constraints
1 ≤ len(weights) ≤ 1001 ≤ weights[i] ≤ 10001 ≤ capacity ≤ 10_0001 ≤ max_per_bin ≤ 50- If
weightsis empty, return0. - If any single item's weight exceeds
capacity, return-1. - Ties in optimal packing strategies are irrelevant — only the count matters.
Examples
Example 1
Input: min_bins([3, 5, 2, 4, 1], 7, 3)
Output: 3
Example 2
Input: min_bins([10, 10, 10], 10, 1)
Output: 3
Example 3
Input: min_bins([1, 2, 3, 4, 5], 15, 5)
Output: 1
Hints
Hint 1
Sort the items in descending order of weight before running DP — this tends to prune the search space dramatically by failing fast when heavy items cannot share a bin.
Hint 2
Define your DP state as (index_of_next_item_to_pack, current_bin_weight_so_far, items_in_current_bin) → minimum total bins opened so far. Use memoization (functools.lru_cache or a dict).
Hint 3
When you place an item, you can either add it to the current bin (if both weight and count constraints allow) or close the current bin and start a new one. The answer is dp(0, 0, 0) + 1 if you model 'bins opened so far' as closed bins only.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Observations
-
Feasibility check first: if any item weight exceeds
capacity, return-1immediately — no valid packing exists. -
Sorting heuristic: sorting items in descending weight order is critical for pruning. Heavier items placed first means the DP state space explored tends to be much smaller because large infeasible branches are detected early.
-
DP formulation: define
dp(i, cur_weight, cur_count)as the minimum number of already-closed bins needed to pack items
i..n-1, given that the currently open bin has accumulated weightcur_weightand holdscur_countitems.At each step, there are two transitions:
- Fit in current bin: if
cur_weight + w[i] ≤ capacityandcur_count + 1 ≤ max_per_bin, add the item to the open bin. - Open a new bin: close the current bin (cost +1), open a new bin with just
w[i]in it.
Base case:
dp(n, _, _) = 0(no more items, zero more closings needed). - Fit in current bin: if
-
Final answer:
dp(0, 0, 0) + 1— the+1accounts for the last open bin which is never explicitly "closed" in the recursion.
Correctness
The recursion exhaustively explores every valid packing configuration (via memoization it avoids redundant sub-problems). Because the number of distinct states is bounded by n × capacity × max_per_bin, the memoized recursion terminates and finds the global optimum.
Complexity
- States: O(n · capacity · max_per_bin)
- Transitions per state: O(1)
- Time: O(n · capacity · max_per_bin)
- Space: O(n · capacity · max_per_bin) for the memo table plus O(n) recursion stack
With n ≤ 100, capacity ≤ 10,000, max_per_bin ≤ 50, the worst-case state count is 50,000,000 — tight but acceptable in practice because many states are never reached (especially with descending sort).
Reference Solution
from typing import List
import functools
def min_bins(weights: List[int], capacity: int, max_per_bin: int) -> int:
if not weights:
return 0
if max(weights) > capacity:
return -1
w = sorted(weights, reverse=True)
n = len(w)
@functools.lru_cache(maxsize=None)
def dp(i, cur_weight, cur_count):
if i == n:
return 0
item = w[i]
best = float('inf')
# Option 1: add to current bin
if cur_weight + item <= capacity and cur_count + 1 <= max_per_bin:
best = min(best, dp(i + 1, cur_weight + item, cur_count + 1))
# Option 2: close current bin, start new one
best = min(best, 1 + dp(i + 1, item, 1))
return best
return dp(0, 0, 0) + 1