Skip to content

Commit 140d8f1

Browse files
committed
added Fractional Knapsack
1 parent cd07f74 commit 140d8f1

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

Greedy/FractionalKnapsack/README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Fractional Knapsack
2+
3+
## Problem:
4+
5+
Given `weights`: list of weights where `weights[i]` represents the weight of `i-th` item,
6+
`values` : list of values where `values[i]` represents the value of `i-th` item,
7+
and `capacity`, total weight available,
8+
Find the maximum values that can be achieved within the limit of total weight.
9+
10+
**Unlike, 0-1 Knapsack Problem, a fraction/portion of an item can be used**
11+
12+
## Example:
13+
14+
```
15+
weights = [1,2,3]
16+
values = [6,10,12]
17+
capacity = 5
18+
19+
Output: 24
20+
Explanation: Whole of first two items and 2/3 of the last item
21+
weight = 1+2+(2/3)*3 = 5
22+
value = 6+10+(2/3)*12 = 24
23+
```
24+
25+
## Note:

Greedy/FractionalKnapsack/solution.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from collections import defaultdict
2+
3+
4+
def fractionalKnapsack(weights, values, capacity):
5+
maxValue = 0
6+
unitValues = defaultdict(int)
7+
for i in range(len(weights)):
8+
unitValues[values[i]/weights[i]] += weights[i]
9+
while capacity:
10+
valueToAdd = max(unitValues)
11+
weightToAdd = min(capacity, unitValues[valueToAdd])
12+
maxValue += valueToAdd * weightToAdd
13+
unitValues[valueToAdd] -= weightToAdd
14+
if unitValues[valueToAdd] == 0:
15+
del unitValues[valueToAdd]
16+
capacity -= weightToAdd
17+
return maxValue
18+
19+
20+
weights = [2, 1, 3]
21+
values = [10, 6, 12]
22+
capacity = 5
23+
print(fractionalKnapsack(weights, values, capacity))

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ Languages used: Java and Python
8686

8787
- [Assign Cookies](Greedy/AssignCookies)
8888
- [Car Pooling](Greedy/CarPooling)
89+
- [Fractional Knapsack](Greedy/FractionalKnapsack)
8990
- [Maximize Sum after K Negations](Greedy/MaximizeSumAfterKNegations)
9091
- [Maximum Score Words](Greedy/MaximumScoreWords)
9192
- [Score After Flipping Matrix](Greedy/ScoreAfterFlippingMatrix)

0 commit comments

Comments
 (0)