Fewest Items to Hit an Exact Weight Target
Dynamic ProgrammingAuto-graded · 22 test casesLast updated
Tests whether a candidate can apply 0/1 knapsack DP to find the minimum number of items from a list whose weights sum to exactly a given target.
Problem
You are managing a cargo loading system. Each shipment has a recorded weight in kilograms. Given a list of shipment weights and a target load, find the fewest shipments you can select so their combined weight equals the target exactly. If no selection achieves the exact target, return -1.
Each shipment in the list is a distinct physical package and can be chosen at most once.
Constraints
1 <= len(weights) <= 10001 <= weights[i] <= 10000 <= target <= 5000- If
targetis0, the answer is0(select nothing). - Duplicate values in
weightsrepresent separate shipments and may each be selected independently.
Examples
Example 1
Input: min_shipments_for_target([2, 3, 5, 7], 10)
Output: 2
Example 2
Input: min_shipments_for_target([1, 1, 1], 4)
Output: -1
Hints
Hint 1
Start by asking yourself: can a shipment be reused? Work out a small example with repeated values to confirm the answer, then let that guide your DP formulation.
Hint 2
Define dp[s] as the minimum number of shipments needed to reach sum s exactly. Think carefully about the order in which you update dp[s] when processing each shipment weight — the direction of your inner loop is the crux of the problem.
Hint 3
If you iterate the inner loop from high to low, each shipment is counted at most once per pass. Convince yourself why iterating low to high would overcount, then code the correct direction.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Settle the reuse question first
The problem says each shipment is a distinct package that can be chosen at most once. This makes it a 0/1 knapsack problem, not unbounded coin change. Recognising the difference determines the direction of the inner loop — getting that wrong produces a solution that appears correct on most inputs but fails whenever the optimal answer requires using a value only once.
DP formulation
Define dp[s] as the minimum number of shipments from those processed so far whose weights sum to exactly s. Unreachable sums are marked with a sentinel INF = len(weights) + 1 (any real answer is at most len(weights)).
Base case: dp[0] = 0. Everything else starts at INF.
For each shipment of weight w, apply:
dp[s] = min(dp[s], dp[s - w] + 1) for s from target down to w
After all shipments are processed, dp[target] holds the answer, or -1 if it is still INF.
Why descending order is correct
This is the 1-D compression of a 2-D recurrence:
f[i][s] = min(f[i-1][s], f[i-1][s - w_i] + 1)
The right-hand term reads row i-1 at position s - w_i. In the compressed array that means reading dp[s - w] before it has been updated in the current pass. Iterating s from high to low guarantees exactly that, because s - w < s and we have not yet reached that index. Iterating low to high would read the already-updated value, effectively allowing w to be used multiple times — turning the problem into unbounded selection.
Walkthrough on Example 1
weights = [2, 3, 5, 7], target = 10
| After shipment | Notable dp values |
|---|---|
| 2 | dp[2] = 1 |
| 3 | dp[3] = 1, dp[5] = 2 |
| 5 | dp[5] = 1, dp[7] = 2, dp[8] = 2, dp[10] = 3 |
| 7 | dp[7] = 1, dp[9] = 2, dp[10] = min(3, dp[3]+1) = 2 |
Answer: 2 (shipments of weight 3 and 7).
Edge cases
target == 0:dp[0] = 0handles this without special-casing.- No combination reaches the target:
dp[target]staysINF, return-1. - A single shipment equals the target:
dp[target]becomes 1 after that shipment's pass. - All weights exceed the target: the inner loop body never executes for any shipment;
dp[target]remainsINF.
Complexity
- Time: O(n · T), where n =
len(weights)and T =target. Worst case is 1 000 × 5 000 = 5 × 10⁶ operations. - Space: O(T) for the single DP array.
Full solution
from typing import List
def min_shipments_for_target(weights: List[int], target: int) -> int:
INF = len(weights) + 1
dp = [INF] * (target + 1)
dp[0] = 0
for w in weights:
# High-to-low: each shipment is counted at most once.
for s in range(target, w - 1, -1):
if dp[s - w] + 1 < dp[s]:
dp[s] = dp[s - w] + 1
return -1 if dp[target] == INF else dp[target]