File tree Expand file tree Collapse file tree 3 files changed +49
-0
lines changed
Greedy/FractionalKnapsack Expand file tree Collapse file tree 3 files changed +49
-0
lines changed Original file line number Diff line number Diff line change
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:
Original file line number Diff line number Diff line change
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 ))
Original file line number Diff line number Diff line change @@ -86,6 +86,7 @@ Languages used: Java and Python
86
86
87
87
- [ Assign Cookies] ( Greedy/AssignCookies )
88
88
- [ Car Pooling] ( Greedy/CarPooling )
89
+ - [ Fractional Knapsack] ( Greedy/FractionalKnapsack )
89
90
- [ Maximize Sum after K Negations] ( Greedy/MaximizeSumAfterKNegations )
90
91
- [ Maximum Score Words] ( Greedy/MaximumScoreWords )
91
92
- [ Score After Flipping Matrix] ( Greedy/ScoreAfterFlippingMatrix )
You can’t perform that action at this time.
0 commit comments