oneby7

2-D Dynamic Programming Knapsack

546. 0/1 Knapsack

Medium

You have a bag that holds at most capacity units of weight, and n items. Item i is worth val[i] and weighs wt[i].

Choose some of the items so that their total weight is at most capacity. Each item is either taken whole or left out, and it can be taken at most once. Return the largest total value you can carry.

The bag does not have to be full. Taking no items at all is allowed, and it is worth 0.

Example 1

Input: capacity = 9, val = [15, 9, 8, 7], wt = [6, 4, 3, 2]

Output: 24

Explanation: Take the items worth 9, 8 and 7. They weigh 4 + 3 + 2 = 9 and are worth 24. The item worth 15 weighs 6, and with it the best we can add is the item worth 8, for 23.

Example 2

Input: capacity = 3, val = [40, 25], wt = [4, 9]

Output: 0

Explanation: Both items weigh more than the bag holds, so the bag stays empty.

Example 3

Input: capacity = 7, val = [6, 10, 3], wt = [4, 5, 3]

Output: 10

Explanation: The item worth 10 weighs 5 and leaves 2 units of the bag empty. The items worth 6 and 3 fill the bag exactly, but they are worth only 9.

Check your understanding

Work out the answer for this input before you write any code.

capacity = 6 val = [11, 9, 12, 4] wt = [3, 3, 5, 1]

Constraints

  • n == val.length == wt.length
  • 1 ≤ n ≤ 1000
  • 1 ≤ capacity ≤ 104
  • 1 ≤ wt[i] ≤ 104
  • 1 ≤ val[i] ≤ 106

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.