0/1 Knapsack Problem using Dynamic Programming in Python

 


The 0/1 knapsack problem can also be solved using a dynamic programming technique in Python. Dynamic programming involves solving a problem by dividing it into smaller subproblems and storing the solutions to the subproblems in a table, so that they can be reused to solve the original problem.

To solve the 0/1 knapsack problem using dynamic programming in Python, we can use a similar approach to the one described in the previous answer. The main difference is that we will use a table to store the maximum value that can be obtained for each weight up to the maximum weight allowed. The table is filled in a bottom-up manner, starting with the weights 0 to W (where W is the maximum weight allowed), and the values are computed using the following formula:

if weight[i] > j:
  dp[i][j] = dp[i-1][j]
else:
  dp[i][j] = max(dp[i-1][j], value[i] + dp[i-1][j-weight[i]])

Here is the code for a function that solves the 0/1 knapsack problem using dynamic programming in Python:

def knapsack(weight, value, W):
  # Initialize the dp table with zeros
  dp = [[0 for j in range(W+1)] for i in range(len(weight)+1)]
  
  # Iterate over the items
  for i in range(1, len(weight)+1):
    # Iterate over the weights
    for j in range(1, W+1):
      # If the weight of the item is greater than the current weight, the value is the same as the previous item
      if weight[i-1] > j:
        dp[i][j] = dp[i-1][j]
      # Otherwise, the value is the maximum of either the value of the previous item or the value of the current item plus the value of the remaining weight
      else:
        dp[i][j] = max(dp[i-1][j], value[i-1] + dp[i-1][j-weight[i-1]])
  
  # Return the maximum value
  return dp[len(weight)][W]

# Test the function with a sample set of items and a weight constraint
weight = [1, 3, 4, 5]
value = [15, 50, 60, 90]
W = 8
print(knapsack(weight, value, W))  # Output: 100

This implementation of the 0/1 knapsack problem using dynamic programming has a time complexity of O(nW), where n is the number of items and W is the maximum weight allowed. It is a more efficient solution than the greedy approach, as it guarantees to find the globally optimal solution to the 0/1 knapsack problem. However, it may require more memory to store the dp table, which can limit its scalability.





AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page