2-D Dynamic Programming Knapsack
555. Unbounded Knapsack
You are given n kinds of items and a bag that holds at most capacity units of weight. An item of kind
i is worth val[i] and weighs wt[i]. There is no limit on the number of items of each kind, so you can
put the same kind in the bag as many times as you like, or leave it out.
Return the largest total value of items you can put in the bag. Their total weight must be at most
capacity, but the bag does not have to be full. Items cannot be cut: each one goes in whole or not at all.
Example 1
Input: val = [18, 25, 8], wt = [3, 4, 5], capacity = 10
61Explanation: Two items of kind 0 and one of kind 1 weigh 3 + 3 + 4 = 10 and are worth 18 + 18 + 25 = 61. Kind 1 is worth the most per unit of weight, but two of them leave 2 units that no item fits in.
Example 2
Input: val = [9, 20], wt = [4, 6], capacity = 11
29Explanation: One item of each kind weighs 10 and is worth 29. Every weight is even, so the bag can never be filled to exactly 11, and it does not have to be.
Example 3
Input: val = [1000000000, 5]
wt = [2, 10000]
capacity = 9999
4999000000000Explanation: Kind 1 weighs more than the bag holds, so it never fits. Kind 0 fits 4999 times, using 9998 units of weight.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1000val.length = wt.length = n1 ≤ val[i] ≤ 1091 ≤ wt[i] ≤ 1041 ≤ capacity ≤ 104
Clarifying questions
What you would ask an interviewer before writing any code.