Python Program for 0-1 Knapsack Problem
Last Updated : 09 Nov, 2023
Write a Python program for a given N items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible.
Examples:
Input: N = 3, W = 4, profit[] = {1, 2, 3}, weight[] = {4, 5, 1}
Output: 3
Explanation: There are two items which have weight less than or equal to 4. If we select the item with weight 4, the possible profit is 1. And if we select the item with weight 1, the possible profit is 3. So the maximum possible profit is 3. Note that we cannot put both the items with weight 4 and 1 together as the capacity of the bag is 4.
Input: N = 3, W = 3, profit[] = {1, 2, 3}, weight[] = {4, 5, 6}
Output: 0
Python Program for 0-1 Knapsack Problem using Recursion:
A simple solution is to consider all subsets of items and calculate the total weight and profit of all subsets. Consider the only subsets whose total weight is smaller than W. From all such subsets, pick the subset with maximum profit.
Optimal Substructure: To consider all subsets of items, there can be two cases for every item.
- Case 1: The item is included in the optimal subset.
- Case 2: The item is not included in the optimal set.
Step-by-step approach:
The maximum value obtained from ‘N’ items is the max of the following two values.
- Case 1 (include the Nth item): Value of the Nth item plus maximum value obtained by remaining N-1 items and remaining weight i.e. (W-weight of the Nth item).
- Case 2 (exclude the Nth item): Maximum value obtained by N-1 items and W weight.
- If the weight of the ‘Nth‘ item is greater than ‘W’, then the Nth item cannot be included and Case 2 is the only possibility.
Below is the implementation of the above approach:
Python # A naive recursive implementation # of 0-1 Knapsack Problem # Returns the maximum value that # can be put in a knapsack of # capacity W def knapSack(W, wt, val, n): # Base Case if n == 0 or W == 0: return 0 # If weight of the nth item is # more than Knapsack of capacity W, # then this item cannot be included # in the optimal solution if (wt[n-1] > W): return knapSack(W, wt, val, n-1) # return the maximum of two cases: # (1) nth item included # (2) not included else: return max( val[n-1] + knapSack( W-wt[n-1], wt, val, n-1), knapSack(W, wt, val, n-1)) # end of function knapSack # Driver Code if __name__ == '__main__': profit = [60, 100, 120] weight = [10, 20, 30] W = 50 n = len(profit) print knapSack(W, weight, profit, n) # This code is contributed by Nikhil Kumar Singh
Time Complexity: O(2N)
Auxiliary Space: O(N), Stack space required for recursion
Python Program for 0-1 Knapsack Problem using Dynamic Programming:
Memoization Approach for 0/1 Knapsack Problem:
If we get a subproblem the first time, we can solve this problem by creating a 2-D array that can store a particular state (n, w). Now if we come across the same state (n, w) again instead of calculating it in exponential complexity we can directly return its result stored in the table in constant time.
Below is the implementation of the above approach:
Python3 # This is the memoization approach of # 0 / 1 Knapsack in Python in simple # we can say recursion + memoization = DP def knapsack(wt, val, W, n): # base conditions if n == 0 or W == 0: return 0 if t[n][W] != -1: return t[n][W] # choice diagram code if wt[n-1] <= W: t[n][W] = max( val[n-1] + knapsack( wt, val, W-wt[n-1], n-1), knapsack(wt, val, W, n-1)) return t[n][W] elif wt[n-1] > W: t[n][W] = knapsack(wt, val, W, n-1) return t[n][W] # Driver code if __name__ == '__main__': profit = [60, 100, 120] weight = [10, 20, 30] W = 50 n = len(profit) # We initialize the matrix with -1 at first. t = [[-1 for i in range(W + 1)] for j in range(n + 1)] print(knapsack(weight, profit, W, n)) # This code is contributed by Prosun Kumar Sarkar
Time Complexity: O(N * W). As redundant calculations of states are avoided.
Auxiliary Space: O(N * W) + O(N). The use of a 2D array data structure for storing intermediate states and O(N) auxiliary stack space(ASS) has been used for recursion stack
Bottom-up Approach for 0/1 Knapsack Problem:
Since subproblems are evaluated again, this problem has Overlapping Sub-problems property. So the 0/1 Knapsack problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computation of the same subproblems can be avoided by constructing a temporary array K[][] in a bottom-up manner.
Below is the implementation of the above approach:
Python3 # A Dynamic Programming based Python # Program for 0-1 Knapsack problem # Returns the maximum value that can # be put in a knapsack of capacity W def knapSack(W, wt, val, n): K = [[0 for x in range(W + 1)] for x in range(n + 1)] # Build table K[][] in bottom up manner for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: K[i][w] = 0 elif wt[i-1] <= w: K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) else: K[i][w] = K[i-1][w] return K[n][W] # Driver code if __name__ == '__main__': profit = [60, 100, 120] weight = [10, 20, 30] W = 50 n = len(profit) print(knapSack(W, weight, profit, n)) # This code is contributed by Bhavya Jain
Time Complexity: O(N * W). where ‘N’ is the number of elements and ‘W’ is capacity.
Auxiliary Space: O(N * W). The use of a 2-D array of size ‘N*W’.
Space optimized Approach for 0/1 Knapsack Problem using Dynamic Programming:
For calculating the current row of the dp[] array we require only previous row, but if we start traversing the rows from right to left then it can be done with a single row only.
Below is the implementation of the above approach:
Python3 # Python code to implement the above approach def knapSack(W, wt, val, n): # Making the dp array dp = [0 for i in range(W+1)] # Taking first i elements for i in range(1, n+1): # Starting from back, # so that we also have data of # previous computation when taking i-1 items for w in range(W, 0, -1): if wt[i-1] <= w: # Finding the maximum value dp[w] = max(dp[w], dp[w-wt[i-1]]+val[i-1]) # Returning the maximum value of knapsack return dp[W] # Driver code if __name__ == '__main__': profit = [60, 100, 120] weight = [10, 20, 30] W = 50 n = len(profit) print(knapSack(W, weight, profit, n)) # This code is contributed by Suyash Saxena
Time Complexity: O(N * W). As redundant calculations of states are avoided
Auxiliary Space: O(W) As we are using a 1-D array instead of a 2-D array
Please refer complete article on Dynamic Programming | Set 10 ( 0-1 Knapsack Problem) for more details!
Similar Reads
Python Program for Fractional Knapsack Problem
Given the weights and profits of N items, in the form of {profit, weight} put these items in a knapsack of capacity W to get the maximum total profit in the knapsack. In Fractional Knapsack, we can break items to maximize the total value of the knapsack. Example : Input: arr[] = {{60, 10}, {100, 20}
5 min read
Python Program for Subset Sum Problem | DP-25
Write a Python program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input:
7 min read
Python Program for Min Cost Path
Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (inc
2 min read
Python Program For Chocolate Distribution Problem
Given an array of n integers where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are m students, the task is to distribute chocolate packets such that: Each student gets one packet.The difference between the number of chocolat
3 min read
Python Program for Minimum product subset of an array
Given an array a, we have to find the minimum product possible with the subset of elements present in the array. The minimum product can be a single element also. Examples:Â Input : a[] = { -1, -1, -2, 4, 3 } Output : -24 Explanation : Minimum product will be ( -2 * -1 * -1 * 4 * 3 ) = -24 Input : a
3 min read
Python Program for Cutting a Rod | DP-13
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then
3 min read
Python program to find all possible pairs with given sum
Given a list of integers and an integer variable K, write a Python program to find all pairs in the list with given sum K. Examples: Input : lst =[1, 5, 3, 7, 9] K = 12 Output : [(5, 7), (3, 9)] Input : lst = [2, 1, 5, 7, -1, 4] K = 6 Output : [(2, 4), (1, 5), (7, -1)] Method #1: Pythonic Naive This
7 min read
Python Program to calculate Profit Or Loss
Given the Cost Price(CP) and Selling Price(SP) of a product. The task is to calculate the Profit or Loss.Example: Input: CP = 1500, SP = 2000Output: 500 ProfitInput: CP = 3125, SP = 1125Output: 2000 LossFormula: Profit = (Selling Price - Cost Price) Loss = (Cost Price - Selling Price) Program to cal
1 min read
Python3 Program for Equilibrium index of an array
Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in an array A: Example : Input: A[] = {-7, 1, 5, 2, -4, 3, 0} Output: 3 3 is an equilibrium index, because: A[0] + A[1] + A[2] = A[4] + A[5] + A[6]
4 min read
Python Set Coding Practice Problems
Welcome to this article on Python set practice problems! Here, weâll explore a variety of engaging Python set practice questions, including topics like Set Operations, Multiset Operations and more. Youâll also practice solving problems like replacing elements with the least greater element, finding
1 min read