Menu
CoddyTech

0/1 Knapsack Problem

You have n items. Item i weighs weights[i] and is worth values[i]. Your bag carries a total weight of at most capacity. Each item exists once, and you either pack it whole or leave it behind. Return the largest total value you can pack.

Function

knapsack(weights: integer-array, values: integer-array, capacity: integer) → integer
weightsinteger-array
the weight of each item
valuesinteger-array
the value of each item
capacityinteger
the most weight the bag can carry
Returnsinteger
the largest total value of items whose weights fit within capacity

Constraints

  • 1 ≤ n ≤ 100, where n = weights.length = values.length
  • 1 ≤ weights[i] ≤ 1000
  • 1 ≤ values[i] ≤ 104
  • 1 ≤ capacity ≤ 1000

Examples

Input
weights = [4, 2, 3, 5]values = [10, 4, 7, 12]capacity = 7
Output
17
Explanation
Items 0 and 2 weigh 4 + 3 = 7 and are worth 10 + 7 = 17. Packing the most valuable item first (weight 5, value 12) leaves room for item 1 only, for 16.
challenge icon

Follow-up

Suppose the capacity can reach 10^9 while the values add up to at most 10^4. What would you index the table by?

Reset code
def knapsack(weights, values, capacity):
    # Write code here

Test #1

Test #2

Test #3

Arguments

weights = [4, 2, 3, 5]
values = [10, 4, 7, 12]
capacity = 7

Expected Output

17