Skip to content

Commit 534256d

Browse files
committed
0-1 Knapsack Problem
1 parent 6fc3ce3 commit 534256d

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

7-case-studies/Knapsack.md

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
## 0-1 Knapsack Problem
2+
3+
Take or leave an object with a certain value into your knapsack that has a weight limit.
4+
5+
### Greedy for value
6+
Initially you might think to take objects with the highest value. But what if the objects with the highest value also weigh the most, and filling the pack with those is worse value than filling the pack with objects that are worth less but weigh the least?
7+
8+
### Slow, straightforward solution:
9+
Try every combo of objects and pick the one that's best. Brute force.
10+
11+
O(2^n) where n is # of objects for that solution combo. An exponential time.
12+
13+
### Smarter Approach
14+
15+
Instead of just max value for max weight, what if we max value for min weight?
16+
17+
Array to store max value for each weight up to weight limit.
18+
19+
Initialize to zero. We have knapsack of weight 6.
20+
21+
1 2 3 4 5 6 (max)
22+
0 0 0 0 0 0
23+
24+
Here's our objects.
25+
26+
WEIGHT 2 5 4
27+
VALUE 6 9 5
28+
29+
Update index of 2 with value 6, and everything after index 2 also with value 6.
30+
31+
1 2 3 4 5 6 (max)
32+
0 6 6 6 6 6
33+
34+
Next obj has more value, so replace.
35+
36+
1 2 3 4 5 6
37+
0 6 6 6 9 9
38+
39+
Next object is weight 4, but index 4 is already a better value, so it doesn't get replaced.
40+
41+
Now we look at index 1, since our weight 4 obj can add to that index to make an index 5 with weight 5. But 9 is bigger than 5 so it won't replace.
42+
43+
Now we look at index 2, since our weight 4 can add to that index to make an index 6 with weight 11. This is better than the one in index 6! We can replace it.
44+
45+
1 2 3 4 5 6
46+
0 6 6 6 9 11
47+
48+
Out of all these, 11 is the max. This has been solved.
49+
50+
This saves a lot of time with many objects. We have precomputed max values, so we only do this work once to get those numbers.
51+
52+
We iterate through objects and see if we can increase the max value of each possible weight up to our max weight.
53+
54+
Runtime is O(n * W) where W is weight limit of knapsack and n is number of elements. This is a Pseudo-Polynomial Time. A true polynomial time does not have a number besides n (that is, relies only on one variable).
55+
56+
This is a technique known as Dynamic Programming.

0 commit comments

Comments
 (0)