2-D Dynamic Programming Knapsack
546. 0/1 Knapsack
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]
24Explanation: 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]
0Explanation: 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]
10Explanation: 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.
Constraints
n == val.length == wt.length1 ≤ n ≤ 10001 ≤ capacity ≤ 1041 ≤ wt[i] ≤ 1041 ≤ val[i] ≤ 106
Clarifying questions
What you would ask an interviewer before writing any code.