Maximize the value of items packed under a weight limit, each item taken at most once
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: Given item values, item weights and a weight capacity, find the largest total value of a subset of items that fits, where each item is taken whole or not at all and at most once. It tests the take-or-skip recurrence, a compact table over capacities, and the update order that keeps an item from being counted twice.
Constraints
- 1 <= n <= 1000, where n = len(values) = len(weights)
- 1 <= capacity <= 1000
- 1 <= values[i] <= 1000
- 1 <= weights[i] <= 1000
Examples
Input: ([60, 100, 120], [10, 20, 30], 50)
Expected Output: 220
Explanation: First worked example: weights 20 and 30 fill the limit for 220, while a value-per-weight greedy stops at 160.
Input: ([10, 40, 30, 50], [5, 4, 6, 3], 10)
Expected Output: 90
Explanation: Second worked example: weights 4 and 3 give 90 at total weight 7; requiring an exact fill of 10 would give only 70.
Hints
- Try always picking the item with the best value per unit of weight on the first example. That rule takes the weight-10 and weight-20 items and ends at 160, below the correct 220.
- For each item there are only two choices: take it or leave it. What do you need to know about the items you have already decided on to make the next choice well?
- Remember that choosing nothing is allowed. If no item fits, the answer is 0, and the best set does not have to fill the knapsack completely.