AlgoFrames

0/1 knapsack

Standard · Write code · about 15 min

Item i weighs weights[i] and is worth values[i]. A bag holds total weight at most capacity. Each item can go in once or not at all.

Return the largest total value that fits.

Example 1

Input:

[[1,3,4],[15,20,30],4]

Output:

35

A + B weigh 4 and are worth 35; C alone is worth 30.

Example 2

Input:

[[2,3,4],[3,4,6],5]

Output:

7

A + B weigh 5 and are worth 7.

Constraints

  • 1 ≤ n ≤ 200, where n = weights.length = values.length
  • 1 ≤ weights[i] ≤ 200
  • 0 ≤ values[i] ≤ 200
  • 0 ≤ capacity ≤ 200

Learn the idea first: 0/1 and unbounded knapsack, a visual lesson.

More 0/1 and unbounded knapsack problems