There are n items; the i-th item (i = 1, 2, 3…n) has value vi and weight wi. We have a knapsack that can carry at most m. We pick some items to put in it, at most one of each, and obviously the total weight must not exceed m. We want the total value to be as large as possible — so which items do we pick? Assume every number involved is a positive integer.
If you have not thought the knapsack problem through carefully, the first instinct tends to be greedy.
Sort by how valuable an item is, for example, and take the valuable ones first.
But consider this data:
n = 3, m = 3
v = (2, 2, 3)
w = (1, 2, 3)
The “most valuable first” strategy takes the item worth 3 and the knapsack is full — yet if we take the first two items the total value reaches 4.
Sort by value for weight instead: For this data
n = 3, m = 7
v = (2, 3, 4)
w = (3, 4, 5)
Since 2/3 < 3/4 < 4/5, we take the third item first — and once it is in, nothing else fits! Total value 4, while the first two items would have given 5.
The reason is that greedy assumes the global optimum can be built out of each step’s local optimum, whereas in the knapsack problem whether taking a step is optimal depends on the whole — that is, it is “dynamic”. Which is why the knapsack problem is a canonical dynamic-programming problem.
Now look at a fractional knapsack problem:
A traveller has a knapsack that can carry at most m kilograms, and there are n items whose weight and value are w[i] and c[i]. What is the maximum value the traveller can get?
This one is a greedy problem: keep taking the best value-for-weight until the bag is full. So whether greedy works comes down to whether an item may be taken partially.
The knapsack problem then spawns many variants, and the DP formulations differ, so it takes practice to get comfortable with this whole family of problems.
Reference:
51NOD
Baidu Zhidao
Baidu Wenku