
Problem
Solution
Submissions
0/1 Knapsack Problem
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C++ program to solve the 0/1 knapsack problem using dynamic programming. Given a set of items, each with a weight and a value, determine the maximum value you can carry in a knapsack of a given capacity.
Example 1
- Input: weights = [1, 2, 3] values = [10, 15, 40] capacity = 5
- Output: 55
- Explanation:
- Step 1: Create a dynamic programming table to store the maximum value for different subproblems.
- Step 2: Fill the table by considering each item and each capacity value from 0 to the maximum capacity.
- Step 3: For this example, the optimal solution is to take items with weights 2 and 3, giving a total value of 15 + 40 = 55.
- Step 4: Return the maximum value possible.
Example 2
- Input: weights = [1, 1, 1] values = [10, 20, 30] capacity = 2
- Output: 50
- Explanation:
- Step 1: Create a dynamic programming table to store the maximum value for different subproblems.
- Step 2: Fill the table by considering each item and each capacity value from 0 to the maximum capacity.
- Step 3: For this example, the optimal solution is to take the second and third items (values 20 and 30), giving a total value of 50.
- Step 4: Return the maximum value possible.
Constraints
- 1 ≤ number of items ≤ 1000
- 1 ≤ capacity ≤ 1000
- Time Complexity: O(n * capacity), where n is the number of items
- Space Complexity: O(n * capacity)
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 to solve this problem.
- Create a 2D array to store the maximum value that can be obtained with a given capacity and a subset of items.
- Fill the array based on whether each item is included or excluded.
- The value in the last cell of the array will be the maximum value.