KatInterview

Fewest Items to Hit an Exact Weight Target

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingknapsackarrays

Last 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) <= 1000
  • 1 <= weights[i] <= 1000
  • 0 <= target <= 5000
  • If target is 0, the answer is 0 (select nothing).
  • Duplicate values in weights represent 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.