Tutorialspoint
Problem
Solution
Submissions

Solve the 0/1 Knapsack Problem

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 15

Write a Python function that solves the 0/1 Knapsack problem. Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.

Example 1
  • Input: values = [60, 100, 120], weights = [10, 20, 30], capacity = 50
  • Output: 220
  • Explanation:
    • Step 1: Initialize a 2D array dp[n+1][capacity+1] to store maximum values.
    • Step 2: Fill the array using dynamic programming approach.
    • Step 3: For each item, decide whether to include it or not based on which gives higher value.
    • Step 4: We can take the second and third items with weights 20 and 30, and values 100 and 120, for a total value of 220.
Example 2
  • Input: values = [10, 20, 30, 40], weights = [1, 2, 3, 4], capacity = 5
  • Output: 70
  • Explanation:
    • Step 1: Initialize a 2D array for dynamic programming.
    • Step 2: For each item and weight, calculate the maximum value.
    • Step 3: Compare including vs excluding the current item.
    • Step 4: We can take the first, second, and fourth items with weights 1, 2, and 4, and values 10, 20, and 40, for a total value of 70.
Constraints
  • 1 ≤ len(values) ≤ 1000
  • len(values) = len(weights)
  • 1 ≤ capacity ≤ 1000
  • 1 ≤ values[i], weights[i] ≤ 1000
  • Time Complexity: O(n*W), where n is the number of items and W is the capacity
  • Space Complexity: O(n*W)
ArraysDynamic Programming EYAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming with a 2D array dp[i][w] representing the maximum value that can be obtained using the first i items and with a capacity of w
  • Initialize the first row and column of the dp array with 0
  • For each item, consider two cases: include it or exclude it
  • The final result will be in dp[n][capacity]
  • You can optimize space complexity to O(W) by using a 1D array

Steps to solve by this approach:

 Step 1: Create a 2D DP table where dp[i][w] represents maximum value with first i items and capacity w.
 Step 2: Initialize the DP table with zeros.
 Step 3: For each item i and each weight capacity w:
 Step 4: If item weight > current capacity, exclude the item (dp[i][w] = dp[i-1][w]).
 Step 5: If item weight <= current capacity, choose maximum of including or excluding the item.
 Step 6: If including: add item value + dp[i-1][w-weight[i-1]].
 Step 7: Return the value at dp[n][capacity] as the maximum possible value.

Submitted Code :