
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)
Editorial
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. |
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