0/1 Knapsack

Implement knapsack01

Given a set of items, each with a weight and a value, and a bag that can hold at most a given total weight, choose a subset of items — each usable at most once — that maximizes the total value packed into the bag without exceeding its weight capacity. Every item faces one decision: leave it out of the bag, or pack it in if there's room. Leaving it out means the best achievable value at the current capacity is whatever could already be made using the remaining items; packing it in means banking its value and continuing with less capacity to work with for the rest. Since it's never clear in advance which items are worth their weight, both choices are tried wherever an item fits, and the larger of the two resulting totals wins. Because each item is considered exactly once, tracking the best value reachable at every possible capacity — building it up one item at a time — finds the answer directly.

Example 1:

Input: weights = [2,3,4,5], values = [3,4,5,6], capacity = 5

Output: 7

Example 2:

Input: weights = [1,4,3], values = [15,40,30], capacity = 4

Output: 45

Example 3:

Input: weights = [5], values = [10], capacity = 4

Output: 0

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ weights.length = values.length ≤ 20
  • 1 ≤ weights[i], values[i] ≤ 100
  • 0 ≤ capacity ≤ 1000

weights =

[2, 3, 4, 5]

values =

[3, 4, 5, 6]

capacity =

5