0/1 Knapsack

medium · dynamic programming

Given positive integer weights, nonnegative integer values of equal length, and capacity >= 0, return the largest value of a subset whose total weight is at most capacity. Each indexed item can be used at most once, including when multiple items have equal weight/value. Empty input returns 0. At most 100 items and capacity <= 1000. Examples (JSON; null means Python None): Input: {"weights": [2, 3, 4], "values": [4, 5, 7], "capacity": 5} Output: 9 Input: {"weights": [2], "values": [3], "capacity": 4} Output: 3

Starter code

def knapsack(weights: list[int], values: list[int], capacity: int) -> int:
    """Choose each item at most once within a weight budget."""
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

3 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. Me at 2amCharacter joke · No posting date

    My code works. I have no idea why. I am afraid to touch it. I am going to bed.

  2. Rubber DuckCharacter joke · No posting date

    Quack. (Translation: have you tried printing it?)

  3. RecruiterCharacter joke · No posting date

    We loved your energy. We went with the candidate whose code compiled.