721. Backpack Value

Medium3.5 points estimatedArrayDynamic Programming3 hints

A hiker is packing a rucksack that can carry at most capacity kilograms. There are n distinct items; item i weighs weights[i] and is worth values[i]. Every item exists only once, so it is either packed or left behind.

Return the largest total worth of a set of items whose total weight does not exceed capacity. If nothing fits, the answer is 0. The arrays weights and values have the same length.

Aim for time O(n * capacity) and extra space O(capacity).

Example 1

Input:
weights = [4,3,5,2], values = [9,7,12,4], capacity = 8
Output:
19
Explanation:

Packing the items of weight 3 and 5 is worth 7 + 12 = 19, which is the best that fits in 8 kilograms.

Example 2

Input:
weights = [6,7], values = [10,20], capacity = 5
Output:
0
Explanation:

Both items are heavier than the capacity, so nothing can be packed and the answer is 0.

Constraints

1 ≤ n ≤ 200

1 ≤ weights[i] ≤ 1000

1 ≤ values[i] ≤ 1000

1 ≤ capacity ≤ 5000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,000 msC++ 250 msJava 500 msJavaScript 500 msTypeScript 500 ms

Expected complexity

Time
O(n * capacity)
Space
O(capacity)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…