1
1
"""
2
2
A shopkeeper has bags of wheat that each have different weights and different profits.
3
3
Example:
4
- no_of_items = 4
5
- profit = [5, 4, 8, 6]
6
- weight = [1, 2, 4, 5]
7
- max_weight = 5
4
+ no_of_items = 4
5
+ profit = [5, 4, 8, 6]
6
+ weight = [1, 2, 4, 5]
7
+ max_weight = 5
8
8
9
9
Constraints:
10
- - max_weight > 0
11
- - profit[i] >= 0
12
- - weight[i] >= 0
10
+ max_weight > 0
11
+ profit[i] >= 0
12
+ weight[i] >= 0
13
13
14
- Calculate the maximum profit the shopkeeper can make given the maximum weight that can be carried.
14
+ Calculate the maximum profit the shopkeeper can make given the maximum weight
15
+ that can be carried.
15
16
"""
16
17
17
- from functools import lru_cache
18
-
19
-
20
18
def knapsack (
21
- weights : list ,
22
- values : list ,
23
- number_of_items : int ,
24
- max_weight : int ,
25
- index : int ,
26
- memo = None ,
19
+ weights : list , values : list , number_of_items : int , max_weight : int , index : int
27
20
) -> int :
28
21
"""
29
- Optimized Recursive Knapsack with Memoization.
30
-
22
+ Function description is as follows:
31
23
:param weights: List of item weights
32
- :param values: List of corresponding item profits
33
- :param number_of_items: Total number of available items
34
- :param max_weight: Maximum weight capacity of the knapsack
35
- :param index: Current item index being considered
36
- :param memo: Dictionary to store computed results for optimization
37
- :return: Maximum profit possible
24
+ :param values: List of item profits corresponding to the weights
25
+ :param number_of_items: Number of available items
26
+ :param max_weight: Maximum weight that can be carried
27
+ :param index: The item index currently being checked
28
+ :return: Maximum expected gain
38
29
39
30
>>> knapsack([1, 2, 4, 5], [5, 4, 8, 6], 4, 5, 0)
40
31
13
@@ -44,31 +35,14 @@ def knapsack(
44
35
if index == number_of_items :
45
36
return 0
46
37
47
- if memo is None :
48
- memo = {}
49
-
50
- # If already computed, return stored value
51
- if (index , max_weight ) in memo :
52
- return memo [(index , max_weight )]
53
-
54
- # Case 1: Skip the current item
55
- ans1 = knapsack (weights , values , number_of_items , max_weight , index + 1 , memo )
56
-
57
- # Case 2: Include the current item (if weight allows)
38
+ ans1 = knapsack (weights , values , number_of_items , max_weight , index + 1 )
58
39
ans2 = 0
59
40
if weights [index ] <= max_weight :
60
41
ans2 = values [index ] + knapsack (
61
- weights ,
62
- values ,
63
- number_of_items ,
64
- max_weight - weights [index ],
65
- index + 1 ,
66
- memo ,
42
+ weights , values , number_of_items , max_weight - weights [index ], index + 1
67
43
)
68
-
69
- # Store and return the maximum value obtained
70
- memo [(index , max_weight )] = max (ans1 , ans2 )
71
- return memo [(index , max_weight )]
44
+
45
+ return max (ans1 , ans2 )
72
46
73
47
74
48
if __name__ == "__main__" :
0 commit comments