AOA Exp 4 b44
AOA Exp 4 b44
Experiment No.04
A.1 Aim:
Write a program to implement Knapsack Problem using Greedy Method Approach.
A.2 Prerequisite:
A.3 Outcome:
After successful completion of this experiment students will be able apply greedy method
approach to different problems to find optimal solution and analyze the complexity of the
problem.
A.4 Theory:
- Fractional Knapsack
- 0/1 Knapsack
Fractional Knapsack
In this case, items can be broken into smaller pieces, so that fraction of item can be
selected. According to the problem statement,
In this version of Knapsack problem, items can be broken into smaller piece i.e.
fraction xi of ith item.
The ith item contributes the weight xi.wi. to the total weight in the knapsack and profit xi.pi
to the total profit.
Subject to constraint
It is clear that an optimal solution must fill the knapsack exactly, otherwise we could add a
fraction of one of the remaining items and increase the overall profit.
In this context, first we need to sort those items according to the value of pi/wi so that
Time Complexity:
If the provided items are already sorted into a decreasing order of pi/wi, then the while
loop takes a time in O(n); Therefore, the total time including the sort is in O(n logn).
PART B
(PART B : TO BE COMPLETED BY STUDENTS)
Learning:
We learned that the greedy approach provides quick approximations but does not guarantee
optimality in all cases.
B.4 Conclusion:
The Greedy Method efficiently solves the Fractional Knapsack Problem by prioritizing items with the
highest value-to-weight ratio. However, it is not optimal for the 0/1 Knapsack Problem, highlighting the need for
dynamic programming or other approaches in such cases.
Ans:- The greedy algorithm can be efficient for some problems, but not always. It works well
when the problem has the greedy choice property (local decisions lead to an optimal solution)
and optimal substructure. Problems like Huffman coding or Dijkstra's algorithm are good
examples.
However, it's not always optimal. In problems like the 0/1 Knapsack or Traveling Salesman,
greedy algorithms may fail to find the best solution. So, while they can be fast and simple, their
efficiency depends on the problem's structure.
1. Approach:
o Greedy: Makes local, optimal choices at each step.
o Dynamic Programming: Solves subproblems and stores solutions for future use.
2. Optimality:
o Greedy: Doesn’t always guarantee the best solution.
o Dynamic Programming: Guarantees an optimal solution.
3. Efficiency:
o Greedy: Faster (O(n), O(n log n)).
o Dynamic Programming: Slower but ensures correctness (O(n²), O(n³)).
In short, greedy is faster but not always optimal, while dynamic programming guarantees
optimal solutions but can be slower.
These problems benefit from making locally optimal choices to achieve global solutions.
************************