@@ -46,21 +46,17 @@ def knapsack_recur(capacity: int, counter: int) -> int:
46
46
# If weight of the nth item is more than Knapsack of capacity,
47
47
# then this item cannot be included in the optimal solution,
48
48
# else return the maximum of two cases:
49
- # (1) not included
50
- # (2) nth item included one or more times (0-N), if allow_repetition is True
49
+ # (1) nth item included one or more times (0-N), if allow_repetition is True
51
50
# nth item included only once (0-1), if allow_repetition is False
51
+ # (2) not included
52
52
if weights [counter - 1 ] > capacity :
53
53
return knapsack_recur (capacity , counter - 1 )
54
54
else :
55
+ left_capacity = capacity - weights [counter - 1 ]
56
+ new_value_included = values [counter - 1 ] + knapsack_recur (
57
+ left_capacity , not allow_repetition ? counter - 1 : counter
58
+ )
55
59
without_new_value = knapsack_recur (capacity , counter - 1 )
56
- if allow_repetition :
57
- new_value_included = values [counter - 1 ] + knapsack_recur (
58
- capacity - weights [counter - 1 ], counter
59
- )
60
- else :
61
- new_value_included = values [counter - 1 ] + knapsack_recur (
62
- capacity - weights [counter - 1 ], counter - 1
63
- )
64
60
return max (new_value_included , without_new_value )
65
61
66
62
return knapsack_recur (capacity , counter )
0 commit comments