Solution: The 0/1 Knapsack Problem
This review provides a detailed analysis of the different ways to solve the knapsack problem.
Solution 1: brute force
def knap_sack_recursive(profits, profits_length, weights, capacity, current_index):"""Finds the maximum value that can be put in a knapsack:param profits: The profit that can be gained by each item:param profits_length: The number of pieces of jewelry:param weights: The weight of each piece of jewelry:param capacity: The maximum weight that the knapsack can hold:param current_index: Current index of the weights:return: Maximum value that can be put in a knapsack"""# Base Caseif capacity <= 0 or current_index >= profits_length or current_index < 0:return 0# If weight of the nth item is more than Knapsack, then# this item cannot be included in the optimal solutionprofit1 = 0if weights[current_index] <= capacity:profit1 = profits[current_index] + knap_sack_recursive(profits, profits_length, weights,capacity - weights[current_index], current_index + 1)profit2 = knap_sack_recursive(profits, profits_length, weights, capacity, current_index + 1)# Return the maximum of two cases:# (1) nth item included# (2) not includedreturn max(profit1, profit2)def knap_sack(profits, profits_length, weights, capacity):"""Finds the maximum value that can be put in a knapsack:param profits: The profit that can be gained by each:param profits_length: The number of pieces of jewelry:param weights: The weight of each piece of jewelry:param capacity: The maximum weight that the knapsack can hold:return: Maximum value that can be put in a knapsack"""return knap_sack_recursive(profits, profits_length, weights, capacity, 0)# Driver code to test the above functionif __name__ == '__main__':profits = [1, 6, 10, 16] # The values of the jewelryweights = [1, 2, 3, 5] # The weight of eachprint("Total knapsack profit = ", knap_sack(profits, 4, weights, 7))print("Total knapsack profit = ", knap_sack(profits, 4, weights, 6))
Explanation
We start from the beginning of the weight
list and check if the item is within the maximum capacity on line 20.
For each item starting from the end:
- create a new set which INCLUDES item ‘i’ if the total weight does not exceed the capacity
and recursively process the remaining capacity and items. Save the result in
profit1
(line 20). - create a new set WITHOUT item ‘i’, recursively process the remaining items, and save the result in the variable,
profit2
(line 23).
Return the set from the above two sets with higher profit (line 28).
Let’s draw the recursive calls to see if there are any overlapping subproblems. As we can see, in each recursive call, the profits and weights lists remain constant and only the capacity and the current index change. For simplicity, let’s denote capacity with j
and current index with n
:
Time complexity
The time complexity of the algorithm above is ...
Access this course and 1400+ top-rated courses and projects.