File tree 2 files changed +35
-0
lines changed
2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -143,6 +143,7 @@ A place where I upload my daily practice on Data Structure and Algorithm problem
143
143
| 45| [ Max_Sum_Increasing_Subsequence] ( algoexpert.io/questions/Max_Sum_Increasing_Subsequence.md ) | [ Python] ( algoexpert.io/python/Max_Sum_Increasing_Subsequence.py ) |
144
144
| 46| [ Longest_Common_Subsequence] ( algoexpert.io/questions/Longest_Common_Subsequence.md ) | [ Python] ( algoexpert.io/python/Longest_Common_Subsequence.py ) |
145
145
| 47| [ Water_Area] ( algoexpert.io/questions/Water_Area.md ) | [ Python] ( algoexpert.io/python/Water_Area.py ) |
146
+ | 48| [ Knapsack_Problem] ( algoexpert.io/questions/Knapsack_Problem.md ) | [ Python] ( algoexpert.io/python/Knapsack_Problem.py ) |
146
147
147
148
148
149
Original file line number Diff line number Diff line change
1
+
2
+
3
+ # O(N*Capacity) time | # O(N*Capacity) space
4
+ def knapSackProblem (items , capacity ):
5
+ knapSackValues = [[0 for x in range (0 , capacity ) + 1 ] for y in range (0 , len (items ) + 1 )]
6
+ for i in range (1 , len (items ) + 1 ):
7
+ currentWeight = items [i - 1 ][1 ]
8
+ currentValue = items [i - 1 ][0 ]
9
+ for individualCapacity in range (0 , capacity + 1 ):
10
+ if currentWeight > capacity :
11
+ knapSackValues [i ][individualCapacity ] = knapSackValues [i - 1 ][individualCapacity ]
12
+ else :
13
+ knapSackValues [i ][individualCapacity ] = max (knapSackValues [i - 1 ][individualCapacity ], knapSackValues [i - 1 ][individualCapacity - currentWeight ] + currentValue )
14
+ return [knapSackValues [- 1 ][- 1 ], getKnapsackItems (knapSackValues , items )]
15
+
16
+
17
+ def getKnapsackItems (knapSackValues , items ):
18
+ sequence = []
19
+ i = len (knapSackValues ) - 1
20
+ individualCapacity = len (knapSackValues [0 ]) - 1
21
+ while i > 0 :
22
+ if knapSackValues [i ][individualCapacity ] == knapSackValues [i - 1 ][individualCapacity ]:
23
+ i -= 1
24
+ else :
25
+ sequence .append (i - 1 )
26
+ individualCapacity -= items [i - 1 ][1 ]
27
+ i -= 1
28
+ if individualCapacity == 0 :
29
+ break
30
+ return list (reversed (sequence ))
31
+
32
+
33
+
34
+
You can’t perform that action at this time.
0 commit comments