Search⌘ K
AI Features

0/1 Knapsack

Understand how to solve the 0 1 Knapsack problem by selecting items to maximize total value without exceeding capacity. Explore dynamic programming techniques to implement efficient solutions using memoization and tabulation.

Statement

You are given nn items whose weights and values are known, as well as a knapsack to carry these items. The knapsack cannot carry more than a certain maximum weight, known as its capacity.

You need to maximize the total value of the items in your knapsack, while ensuring that the sum of the weights of the selected items does not exceed the capacity of the knapsack.

If there is no combination of weights whose sum is within the capacity constraint, return 00.

Notes:

  1. An item may not be broken up to fit into the knapsack, i.e., an item either goes into the knapsack in its entirety or not at all.
  2. We may not add an item more than once to the knapsack.

Constraints:

  • 11 \leq capacity 1000\leq 1000
  • 11 \leq values.length 500\leq 500
  • weights.length ==== values.length
  • 11 \leq values[i] 1000\leq 1000
  • 11 \leq weights[i] \leq capacity

Examples

canvasAnimation-image
1 / 2

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

0/1 Knapsack

1.

You have three items with weights 22, 33, and 44, respectively. You have a knapsack with a capacity of 77. How many different combinations of items can you include in the knapsack?

A.

3

B.

4

C.

5

D.

6


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground:

Java
usercode > FindMaxKnapsackProfit.java
import java.util.*;
class FindMaxKnapsackProfit {
public static int findMaxKnapsackProfit(int capacity, int [] weights, int [] values) {
// Replace this placeholder return statement with your code
return 0;
}
}
0/1 Knapsack