|
| 1 | +# Knapsack Problem (Greedy algorithm) |
| 2 | + |
| 3 | +#### Problem Statement |
| 4 | + |
| 5 | +Given a set of items, each with weight and a value, determine the number of each item included in a collection so that the total weight is less than or equal to the given limit and the total value is as large as possible. |
| 6 | + |
| 7 | +##### Greedy method will always provide an optimal solution with fractional knapsack problem. |
| 8 | + |
| 9 | +#### Time Complexity |
| 10 | + |
| 11 | +O(nlog n) Worst Case |
| 12 | + |
| 13 | +#### Example |
| 14 | + |
| 15 | +``` |
| 16 | +Lets assume the capacity of knapsack, W = 60 |
| 17 | +value = [280, 100, 120, 120] |
| 18 | +weight = [40, 10, 20, 24] |
| 19 | +
|
| 20 | +Ratio(V/W) = 7,10,6,5 |
| 21 | +Say those items as A,B,C,D |
| 22 | +next, the items should be sorted in descending order based on the ratio of value by weight to get maximum profit |
| 23 | +First and foremost, B was picked since its weight is smaller than the knapsack's capacity. The next item, A, is chosen since the knapsack's available capacity is more than A's weight. C is now the next item on the list. However, the entire item cannot be chosen because the knapsack's remaining capacity is less than C's weight. |
| 24 | +As a result, the C proportion (60–50)/20) |
| 25 | +The knapsack's capacity is now equal to the specified items. |
| 26 | +As a result, no more items can be chosen. |
| 27 | +
|
| 28 | +10 + 40 + 20*(10/20) = 60 is the total weight of the chosen goods. |
| 29 | +
|
| 30 | +100+280+120*(10/20)=380+60=440 is the total profit. |
| 31 | +
|
| 32 | +This is the most suitable option. |
| 33 | +
|
| 34 | +We won't be able to make more money by combining diverse things. |
| 35 | +
|
| 36 | +``` |
| 37 | + |
| 38 | +#### Code Implementation Links |
| 39 | + |
| 40 | +- [C++](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/knapsack.cpp) |
| 41 | +- [Python](https://github.com/TheAlgorithms/Python/tree/master/knapsack) |
| 42 | +- [C-Sharp](https://github.com/TheAlgorithms/C-Sharp/tree/master/Algorithms/Knapsack) |
| 43 | + |
| 44 | +#### Video Explanation |
| 45 | + |
| 46 | +[A CS50 video explaining the Greedy Algorithm](https://www.youtube.com/watch?v=Ou9OA0yQCYA) |
0 commit comments