Unit Weight Knapsack
GooglePhone screenMedium
You are given several item types. Type i has value values[i] and counts[i] available copies. Every copy weighs 1, and a bag holds at most capacity copies in total.
Implement max_value(values, counts, capacity) that returns the largest possible sum of values of copies placed in the bag.
Part 1: Maximize bag value
Choose how many copies of each type to put in the bag: at most counts[i] copies of type i, and at most capacity copies in total. Return the largest possible sum of the chosen copies' values.
You do not have to fill the bag, so a copy with a negative value is never worth taking, and an empty bag is worth 0.
- Example 1
- counts
[2,1,1]- values
[5,3,8]- capacity
3- Output
18
Why: The best three copies are one 8 and two 5s, for 8 + 5 + 5 = 18.
- Example 2
- counts
[5,1]- values
[-2,4]- capacity
10- Output
4
Why: Type 0 has five copies worth -2 each, and type 1 has one copy worth 4. Taking any -2 copy would lower the total, so the bag skips all of them. Taking the single 4 copy gives the largest total, 4.
Constraints
1 <= len(values) <= 10^5len(counts) == len(values)-10^6 <= values[i] <= 10^61 <= counts[i] <= 10^90 <= capacity <= 10^9