Start free

Expert · Dynamic programming · 213 of 264

Knapsack

Choose items to put in a bag without going over its capacity, making the total value as large as possible. Each item can be taken once.

Input: n and the capacity (up to 1000), then n lines "weight value". Output: the largest total value.

Examples

Input
3 50
10 60
20 100
30 120
Output
220
Input
1 5
6 10
Output
0
Input
4 7
1 1
3 4
4 5
5 7
Output
9

One more test checks other inputs when you press Check.

Stuck? The idea behind dynamic programming

Break the problem into smaller ones that repeat, and keep each answer in a table so it is worked out only once.

Decide what one cell of the table means ("the best total using the first i items"), how it follows from earlier cells, and where it starts.

n = 10
ways = [0] * (n + 1)
ways[0] = 1
for i in range(1, n + 1):
    ways[i] = ways[i - 1] + (ways[i - 2] if i >= 2 else 0)
print(ways[n])  # climbing 10 stairs, 1 or 2 at a time

Watch for: Fill the table in an order where every cell it needs is already filled.

All the dynamic programming exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More dynamic programming exercises