Knapsack 0/1 Optimization

The 0/1 knapsack problem asks for the greatest total value that can be carried in a single container of fixed capacity. Each item has a positive integer weight and a positive integer value, and every item may be taken at most once: there is no way to take a fraction of an item and no way to take two copies. The container starts empty, and the sum of the weights of the chosen items must not exceed the capacity.

Formally, with weights[i] and values[i] for i from 0 to n - 1, pick a subset S of indices so that the sum of weights over S is at most capacity and the sum of values over S is as large as possible. Return that maximum value. If no item fits, the correct answer is 0, because the empty subset is always allowed.

The decision for each item is binary: take it or skip it. That structure yields the classic two-state recurrence: the best value for the first i items and remaining capacity c is the better of skipping item i, or taking it when its weight fits and adding its value to the best result for the first i - 1 items at capacity c - w. A rolling one-dimensional table over capacity gives O(n * capacity) time and O(capacity) space. Greedy selection by value-to-weight ratio is not correct here, because an item with a high ratio can block a combination that fits the capacity far better.

Examples
Input: [[2,3,4],[100,200,300],5]
Output: 300
Hints

Knapsack 0/1 Optimization

The 0/1 knapsack problem asks for the greatest total value that can be carried in a single container of fixed capacity. Each item has a positive integer weight and a positive integer value, and every item may be taken at most once: there is no way to take a fraction of an item and no way to take two copies. The container starts empty, and the sum of the weights of the chosen items must not exceed the capacity.