nathanwailes

0/1 Knapsack - DP

Jun 8th, 2024 (edited)
405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. """
  2. This function knapsack takes the weights and values of the items, as well as the capacity of the knapsack, and returns the maximum value that can be obtained.
  3.  
  4. Explanation:
  5.  
  6. - weights: A list of weights of the items.
  7. - values: A list of values of the items.
  8. - capacity: The maximum weight capacity of the knapsack.
  9. - dp[i][w]: Represents the maximum value that can be obtained using the first i items with a knapsack capacity of w.
  10. - The algorithm uses a 2D list dp where dp[i][w] represents the maximum value that can be obtained with the first i items and a knapsack capacity of w. The solution builds up this table iteratively, using the property that the optimal solution to a problem can be constructed from the optimal solutions to its subproblems.
  11. """
  12.  
  13. def knapsack(weights, values, capacity):
  14.     n = len(weights)
  15.     dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
  16.  
  17.     for i in range(1, n + 1):
  18.         for w in range(1, capacity + 1):
  19.             if weights[i-1] <= w:
  20.                 dp[i][w] = max(dp[i-1][w], dp[i-1][w-weights[i-1]] + values[i-1])
  21.             else:
  22.                 dp[i][w] = dp[i-1][w]
  23.  
  24.     return dp[n][capacity]
  25.  
  26. # Example usage:
  27. weights = [1, 2, 3, 4]
  28. values = [1, 2, 5, 6]
  29. capacity = 7
  30. max_value = knapsack(weights, values, capacity)
  31. print(f"Maximum value in knapsack: {max_value}")
Advertisement
Add Comment
Please, Sign In to add comment