Tutorialspoint
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)
Dynamic Programming ZomatoSamsung
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 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.

Steps to solve by this approach:

 Step 1: Create a 2D array dp[n+1][capacity+1] to store maximum value for each capacity.

 Step 2: Initialize base cases: dp[0][j] = 0 for all j, dp[i][0] = 0 for all i.
 Step 3: For each item i and each capacity j, consider two cases:
 Step 4: If current item's weight is less than or equal to capacity j, choose maximum of including or excluding item.
 Step 5: Otherwise, if weight exceeds capacity, exclude the current item.
 Step 6: Return dp[n][capacity] as the maximum value that can be achieved.

Submitted Code :