InferenceAI

Enter at least two characters to search.

Start free

Knapsack Best Value

mediumDynamic Programming25 min25 XP

Each item has a weight and a value and can be taken at most once. Return the maximum total value with total weight at most capacity.

dp[w]=max⁡(dp[w],  dp[w−wi]+vi)dp[w] = \max(dp[w],\; dp[w - w_i] + v_i)

Requirements

  • O(n⋅W)O(n \cdot W) time and O(W)O(W) space: loop the capacity downwards so each item is used at most once.

Examples

EXAMPLE WALKTHROUGHclassic

A guided view of the published example, not a trace of your code.

INPUT[[1,3,4,5],[1,4,5,7],7]
TASKknapsack_best_value()
EXPECTED OUTPUT9

Start with the input values shown in this example.

Example 1 of 3

Input: weights = [1,3,4,5], values = [1,4,5,7], capacity = 7

Output: 9

Explanation: classic

Input: weights = [10,20,30], values = [60,100,120], capacity = 50

Output: 220

Explanation: textbook

Input: weights = [5], values = [10], capacity = 4

Output: 0

Explanation: too heavy

Hint 1

dp[w] is the best value with weight limit w using the items processed so far.

Topics

DSADynamic ProgrammingPython