KatInterview

Minimum Containers for Target Volume

Dynamic ProgrammingAuto-graded · 23 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingunbounded-knapsackbacktracking

Last updated

Find the minimum combination of reusable containers to reach an exact target total volume, or return None if impossible.

You are tasked with filling a storage tank to an exact volume. You have access to an unlimited supply of containers, where each unique size is given in an array canisters.

Write a function that returns a list containing the minimum total number of containers needed to reach the exact volume specified by target.

  • If there are multiple valid choices that yield the minimum count, you may return any valid combination.
  • If it is impossible to sum up to the exact target volume using the given container sizes, return None.
  • If target is 0, return an empty list [].

Constraints

  • 1 <= len(canisters) <= 50
  • 1 <= canisters[i] <= 10^4
  • All integers in canisters are distinct.
  • 0 <= target <= 10^4

Examples

Example 1

Input: min_canisters_to_target([1, 5, 10, 25], 30)

Output: [5, 25]

Example 2

Input: min_canisters_to_target([2], 3)

Output: None

Example 3

Input: min_canisters_to_target([4, 6, 9], 15)

Output: [6, 9]

Hints

Hint 1

A greedy strategy of choosing the largest container first will fail for cases like target = 12 with sizes [9, 6, 1]. What algorithm considers all optimal subproblem choices?

Hint 2

Think of this as the classic Coin Change problem, but instead of returning just the count, you need to reconstruct the actual items used.

Hint 3

Maintain an array `dp` where `dp[v]` is the minimum containers to form volume `v`, and a tracking array `prev` to store which container size achieved that minimum for volume `v`.