Design & Analysis of Algorithms: Bits, Pilani - K. K. Birla Goa Campus
Design & Analysis of Algorithms: Bits, Pilani - K. K. Birla Goa Campus
Lecture No. 12
1
The 0-1 Knapsack Problem
Given: A set S of n items, with each item i having
wi - a positive “weight”
vi - a positive “benefit”
Goal:
Choose items with maximum total benefit but with weight
at most W.
And we are not allowed to take fractional amounts
In this case, we let T denote the set of items we take
Objective : maximize 𝒗𝒊
𝒊∈𝑻
Constraint : 𝒘𝒊 ≤ 𝑾
𝒊∈𝑻
Greedy approach
Possible greedy approach:
Approach1: Pick item with largest value first
Approach2: Pick item with least weight first
Approach3: Pick item with largest value per
weight first
We know that none of the above approaches work
Exercise:
Prove by giving counterexamples.
Brute Force Approach
• Brute Force
The naive way to solve this problem is to go
through all 2n subsets of the n items and pick
the subset with a legal weight that maximizes
the value of the knapsack.
Optimal Substructure
As we did before we are going to solve the problem in
terms of sub-problems.
• Our first attempt might be to characterize a sub-
problem as follows:
Let Ok be the optimal subset of elements from {I0, I1, …,
Ik}.
Observe
Optimal subset from the elements {I0, I1, …, Ik+1} may
not correspond to the optimal subset of elements from
{I0, I1, …, Ik}
That means, the solution to the optimization problem for
Sk+1 might NOT contain the optimal solution from
problem Sk.
where Sk: Set of items numbered 1 to k.
Optimal Substructure
Example: Let W=20
Item Weight Value
I0 3 10
I1 8 4
I2 9 9
I3 8 11
• The best set of items from {I0, I1, I2} is {I0, I1, I2}
• BUT the best set of items from {I0, I1, I2, I3} is {I0, I2, I3}.
Note
1. Optimal solution, {I0, I2, I3} of S3 for does NOT contain the
optimal solution, {I0, I1, I2} of S2
2. {I0, I2, I3} build's upon the solution, {I0, I2}, which is really the
optimal subset of {I0, I1, I2} with weight 12 or less.
(We incorporates this idea in our 2nd attempt)
Recursive Formulation
Sk: Set of items numbered 1 to k.
Define B[k,w] to be the best selection from Sk with weight
at most w
B[k 1, w] if wk w
B[k , w]
max{B[k 1, w], B[k 1, w wk ] bk } else