Knapsack - Algorithms (Student)
Knapsack - Algorithms (Student)
AKC Notes
The Greedy Method - Knapsack Problem
1. Greedy Method
The greedy method is one of the strategies like Divide and conquer used to solve the problems. This
method is used for solving optimization problems. An optimization problem is a problem that
demands either maximum or minimum results. Let's understand through some terms. The main
function of this approach is that the decision is taken on the basis of the currently available
information. Whatever the current information is present, the decision is made without worrying
about the effect of the current decision in future.
This technique is basically used to determine the feasible solution that may or may not be optimal.
The feasible solution is a subset that satisfies the given criteria. The optimal solution is the solution
which is the best and the most favourable solution in the subset.
5. Knapsack Problem
We are given n objects and a knapsack or bag. Object i has a weight w; and the knapsack has a
capacity m. If a fraction xi, 0 ≤ i ≤ 1, of object i is placed into the knapsack, then a profit of p ixi is
earned. The objective is to obtain a filling of the knapsack that maximizes the total profit earned.
Since the knapsack capacity is m, we require the total weight of all chosen objects to be at most m.
Formally, the problem can be stated as
for i := 1 to n do
x[i] := 0.0
U := m;
for i := 1 to n do
{
if (w(i) > U) then break;
x [i] := 1.0;
U := U – w[i];
}
if (i < n) then x[i] := U / w[i];
}
Complexity
The objects are to be sorted into non-decreasing order of pi / wi ratio. But if we disregard the time
to initially sort the objects, the algorithm requires only O(n) time.