Fill the Cargo Bay Exactly

Medium · 2-D & String DP · about 25 min

A cargo plane's bay is balanced only when the load weighs exactly capacity kilograms. Crate i weighs weights[i] and earns values[i]. Each crate can be loaded at most once.

Return the largest total value of a set of crates whose weights add up to exactly capacity, or -1 if no set of crates weighs exactly that much. A capacity of 0 is filled by loading nothing (value 0).

  • 0 <= len(weights) == len(values) <= 100, weights from 1 to 1000, values from 0 to 10000.
  • 0 <= capacity <= 10000.

Examples:

best_exact_load([1, 3, 4], [15, 20, 30], 4) → 35 (crates 0 and 1)

best_exact_load([2, 3], [5, 6], 4) → -1

Hints

  • This is the usual 0/1 knapsack table, but a cell means "weight exactly c", not "weight at most c".
  • Only weight 0 is possible before any crate is considered. Mark every other weight as impossible.
  • Never build on an impossible cell, walk the weights from high to low, and report -1 if the capacity cell is still impossible.

Learn the pattern first: the 2-D & String DP lesson.

More 2-D & String DP problems