The Wayback Machine - https://web.archive.org/web/20240731190203/https://www.geeksforgeeks.org/printing-items-01-knapsack/
Open In App

Printing Items in 0/1 Knapsack

Last Updated : 23 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the items such that sum of the weights of those items of a given subset is smaller than or equal to W. You cannot break an item, either pick the complete item or don’t pick it (0-1 property).
Prerequisite : 0/1 Knapsack
Examples : 
 

Input : val[] = {60, 100, 120};
        wt[] = {10, 20, 30};
        W = 50;
Output : 220 //maximum value that can be obtained
         30 20 //weights 20 and 30 are included. 

Input : val[] = {40, 100, 50, 60};
        wt[] = {20, 10, 40, 30};
        W = 60;
Output : 200
         30 20 10

Approach : 
Let val[] = {1, 4, 5, 7}, wt[] = {1, 3, 4, 5} 
W = 7. 
The 2d knapsack table will look like : 
 

2d knapsack table

Start backtracking from K[n][W].Here K[n][W] is 9.
Since this value comes from the top (shown by grey arrow), the item in this row is not included. Go vertically upward in the table without including this in the knapsack. Now, this value K[n-1][W] which is 9 doesn’t come from the top which means the item in this row is included and go vertically up and then left by the weight of the included item ( shown by black arrow). Continuing this process include weights 3 and 4 with a total value 9 in the knapsack. 
 

 

C++




// CPP code for Dynamic Programming based
// solution for 0-1 Knapsack problem
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
// A utility function that returns maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
 
// Prints the items which are put in a knapsack of capacity W
void printknapSack(int W, int wt[], int val[], int n)
{
    int i, w;
    int K[n + 1][W + 1];
 
    // Build table K[][] in bottom up manner
    for (i = 0; i <= n; i++) {
        for (w = 0; w <= W; w++) {
            if (i == 0 || w == 0)
                K[i][w] = 0;
            else if (wt[i - 1] <= w)
                K[i][w] = max(val[i - 1] +
                    K[i - 1][w - wt[i - 1]], K[i - 1][w]);
            else
                K[i][w] = K[i - 1][w];
        }
    }
 
    // stores the result of Knapsack
    int res = K[n][W];
    cout<< res << endl;
     
    w = W;
    for (i = n; i > 0 && res > 0; i--) {
         
        // either the result comes from the top
        // (K[i-1][w]) or from (val[i-1] + K[i-1]
        // [w-wt[i-1]]) as in Knapsack table. If
        // it comes from the latter one/ it means
        // the item is included.
        if (res == K[i - 1][w])
            continue;   
        else {
 
            // This item is included.
            cout<<" "<<wt[i - 1] ;
             
            // Since this weight is included its
            // value is deducted
            res = res - val[i - 1];
            w = w - wt[i - 1];
        }
    }
}
 
// Driver code
int main()
{
    int val[] = { 60, 100, 120 };
    int wt[] = { 10, 20, 30 };
    int W = 50;
    int n = sizeof(val) / sizeof(val[0]);
     
    printknapSack(W, wt, val, n);
     
    return 0;
}
 
// this code is contributed by shivanisinghss2110


C




// CPP code for Dynamic Programming based
// solution for 0-1 Knapsack problem
#include <stdio.h>
 
// A utility function that returns maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
 
// Prints the items which are put in a knapsack of capacity W
void printknapSack(int W, int wt[], int val[], int n)
{
    int i, w;
    int K[n + 1][W + 1];
 
    // Build table K[][] in bottom up manner
    for (i = 0; i <= n; i++) {
        for (w = 0; w <= W; w++) {
            if (i == 0 || w == 0)
                K[i][w] = 0;
            else if (wt[i - 1] <= w)
                K[i][w] = max(val[i - 1] +
                    K[i - 1][w - wt[i - 1]], K[i - 1][w]);
            else
                K[i][w] = K[i - 1][w];
        }
    }
 
    // stores the result of Knapsack
    int res = K[n][W];   
    printf("%d\n", res);
     
    w = W;
    for (i = n; i > 0 && res > 0; i--) {
         
        // either the result comes from the top
        // (K[i-1][w]) or from (val[i-1] + K[i-1]
        // [w-wt[i-1]]) as in Knapsack table. If
        // it comes from the latter one/ it means
        // the item is included.
        if (res == K[i - 1][w])
            continue;       
        else {
 
            // This item is included.
            printf("%d ", wt[i - 1]);
             
            // Since this weight is included its
            // value is deducted
            res = res - val[i - 1];
            w = w - wt[i - 1];
        }
    }
}
 
// Driver code
int main()
{
    int val[] = { 60, 100, 120 };
    int wt[] = { 10, 20, 30 };
    int W = 50;
    int n = sizeof(val) / sizeof(val[0]);
     
    printknapSack(W, wt, val, n);
     
    return 0;
}


Java




// Java code for Dynamic Programming based
// solution for 0-1 Knapsack problem
 
class GFG {
     
    // A utility function that returns
    // maximum of two integers
    static int max(int a, int b)
    {
        return (a > b) ? a : b;
    }
 
    // Prints the items which are put
    // in a knapsack of capacity W
    static void printknapSack(int W, int wt[],
                             int val[], int n)
    {
        int i, w;
        int K[][] = new int[n + 1][W + 1];
 
        // Build table K[][] in bottom up manner
        for (i = 0; i <= n; i++) {
            for (w = 0; w <= W; w++) {
                if (i == 0 || w == 0)
                    K[i][w] = 0;
                else if (wt[i - 1] <= w)
                    K[i][w] = Math.max(val[i - 1] +
                              K[i - 1][w - wt[i - 1]], K[i - 1][w]);
                else
                    K[i][w] = K[i - 1][w];
            }
        }
 
        // stores the result of Knapsack
        int res = K[n][W];
        System.out.println(res);
 
        w = W;
        for (i = n; i > 0 && res > 0; i--) {
 
            // either the result comes from the top
            // (K[i-1][w]) or from (val[i-1] + K[i-1]
            // [w-wt[i-1]]) as in Knapsack table. If
            // it comes from the latter one/ it means
            // the item is included.
            if (res == K[i - 1][w])
                continue;
            else {
 
                // This item is included.
                System.out.print(wt[i - 1] + " ");
 
                // Since this weight is included its
                // value is deducted
                res = res - val[i - 1];
                w = w - wt[i - 1];
            }
        }
    }
 
    // Driver code
    public static void main(String arg[])
    {
        int val[] = { 60, 100, 120 };
        int wt[] = { 10, 20, 30 };
        int W = 50;
        int n = val.length;
 
        printknapSack(W, wt, val, n);
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# Python3 code for Dynamic Programming
# based solution for 0-1 Knapsack problem
 
# Prints the items which are put in a
# knapsack of capacity W
def printknapSack(W, wt, val, n):
    K = [[0 for w in range(W + 1)]
            for i in range(n + 1)]
             
    # Build table K[][] in bottom
    # up manner
    for i in range(n + 1):
        for w in range(W + 1):
            if i == 0 or w == 0:
                K[i][w] = 0
            elif wt[i - 1] <= w:
                K[i][w] = max(val[i - 1]
                  + K[i - 1][w - wt[i - 1]],
                               K[i - 1][w])
            else:
                K[i][w] = K[i - 1][w]
 
    # stores the result of Knapsack
    res = K[n][W]
    print(res)
     
    w = W
    for i in range(n, 0, -1):
        if res <= 0:
            break
        # either the result comes from the
        # top (K[i-1][w]) or from (val[i-1]
        # + K[i-1] [w-wt[i-1]]) as in Knapsack
        # table. If it comes from the latter
        # one/ it means the item is included.
        if res == K[i - 1][w]:
            continue
        else:
 
            # This item is included.
            print(wt[i - 1])
             
            # Since this weight is included
            # its value is deducted
            res = res - val[i - 1]
            w = w - wt[i - 1]
 
# Driver code
val = [ 60, 100, 120 ]
wt = [ 10, 20, 30 ]
W = 50
n = len(val)
     
printknapSack(W, wt, val, n)
 
# This code is contributed by Aryan Garg.


C#




// C# code for Dynamic Programming based
// solution for 0-1 Knapsack problem
 
using System ;
 
class GFG {
     
    // A utility function that returns
    // maximum of two integers
    static int max(int a, int b)
    {
        return (a > b) ? a : b;
    }
 
    // Prints the items which are put
    // in a knapsack of capacity W
    static void printknapSack(int W, int []wt,
                            int []val, int n)
    {
        int i, w;
        int [,]K = new int[n + 1,W + 1];
 
        // Build table K[][] in bottom up manner
        for (i = 0; i <= n; i++) {
            for (w = 0; w <= W; w++) {
                if (i == 0 || w == 0)
                    K[i,w] = 0;
                else if (wt[i - 1] <= w)
                    K[i,w] = Math.Max(val[i - 1] +
                            K[i - 1,w - wt[i - 1]], K[i - 1,w]);
                else
                    K[i,w] = K[i - 1,w];
            }
        }
 
        // stores the result of Knapsack
        int res = K[n,W];
        Console.WriteLine(res);
 
        w = W;
        for (i = n; i > 0 && res > 0; i--) {
 
            // either the result comes from the top
            // (K[i-1][w]) or from (val[i-1] + K[i-1]
            // [w-wt[i-1]]) as in Knapsack table. If
            // it comes from the latter one/ it means
            // the item is included.
            if (res == K[i - 1,w])
                continue;
            else {
 
                // This item is included.
                Console.Write(wt[i - 1] + " ");
 
                // Since this weight is included its
                // value is deducted
                res = res - val[i - 1];
                w = w - wt[i - 1];
            }
        }
    }
 
    // Driver code
    public static void Main()
    {
        int []val = { 60, 100, 120 };
        int []wt = { 10, 20, 30 };
        int W = 50;
        int n = val.Length;
 
        printknapSack(W, wt, val, n);
    }
}
 
// This code is contributed by Ryuga.


PHP




<?php
// PHP code for Dynamic Programming based
// solution for 0-1 Knapsack problem
 
// Prints the items which are kept in
// a knapsack of capacity W
function printknapSack($W, &$wt, &$val, $n)
{
    $K = array_fill(0, $n + 1,
         array_fill(0, $W + 1, NULL));
 
    // Build table K[][] in bottom up manner
    for ($i = 0; $i <= $n; $i++)
    {
        for ($w = 0; $w <= $W; $w++)
        {
            if ($i == 0 || $w == 0)
                $K[$i][$w] = 0;
            else if ($wt[$i - 1] <= $w)
                $K[$i][$w] = max($val[$i - 1] +
                    $K[$i - 1][$w - $wt[$i - 1]],
                                 $K[$i - 1][$w]);
            else
                $K[$i][$w] = $K[$i - 1][$w];
        }
    }
 
    // stores the result of Knapsack
    $res = $K[$n][$W];
    echo $res . "\n";
     
    $w = $W;
    for ($i = $n; $i > 0 && $res > 0; $i--)
    {
         
        // either the result comes from the top
        // (K[i-1][w]) or from (val[i-1] + K[i-1]
        // [w-wt[i-1]]) as in Knapsack table. If
        // it comes from the latter one/ it means
        // the item is included.
        if ($res == $K[$i - 1][$w])
            continue;    
        else
        {
 
            // This item is included.
            echo $wt[$i - 1] . " ";
             
            // Since this weight is included
            // its value is deducted
            $res = $res - $val[$i - 1];
            $w = $w - $wt[$i - 1];
        }
    }
}
 
// Driver code
$val = array(60, 100, 120);
$wt = array(10, 20, 30);
$W = 50;
$n = sizeof($val);
printknapSack($W, $wt, $val, $n);
 
// This code is contributed by ita_c
?>


Javascript




<script>
     
// JavaScript code for Dynamic Programming based
// solution for 0-1 Knapsack problem  
 
    // A utility function that returns
    // maximum of two integers
    function max(a,b)
    {
        return (a > b) ? a : b;
    }
     
     
    // Prints the items which are put
    // in a knapsack of capacity W
    function printknapSack(W,wt,val,n)
    {
        let i, w;
        let K = new Array(n + 1);
        for( i=0;i<K.length;i++)
        {
            K[i]=new Array(W+1);
            for(let j=0;j<W+1;j++)
            {
                K[i][j]=0;
            }
        }
   
        // Build table K[][] in bottom up manner
        for (i = 0; i <= n; i++) {
            for (w = 0; w <= W; w++) {
                if (i == 0 || w == 0)
                    K[i][w] = 0;
                else if (wt[i - 1] <= w)
                    K[i][w] = Math.max(val[i - 1] +
                        K[i - 1][w - wt[i - 1]],
                        K[i - 1][w]);
                else
                    K[i][w] = K[i - 1][w];
            }
        }
   
        // stores the result of Knapsack
        let res = K[n][W];
        document.write(res+"<br>");
   
        w = W;
        for (i = n; i > 0 && res > 0; i--)
        {
   
            // either the result comes from the top
            // (K[i-1][w]) or from (val[i-1] + K[i-1]
            // [w-wt[i-1]]) as in Knapsack table. If
            // it comes from the latter one/ it means
            // the item is included.
            if (res == K[i - 1][w])
                continue;
            else {
   
                // This item is included.
                document.write(wt[i - 1] + " ");
   
                // Since this weight is included its
                // value is deducted
                res = res - val[i - 1];
                w = w - wt[i - 1];
            }
        }
    }
     
    let val=[60, 100, 120 ];
    let wt=[10, 20, 30 ];
    let  W = 50;
    let n = val.length;
    printknapSack(W, wt, val, n);
     
    // This code is contributed by avanitrachhadiya2155
     
</script>


Output: 

220
30 20

 

Time complexity: O(n*W)

Space complexity: O(n*W)



Previous Article
Next Article

Similar Reads

Maximum sum of values of N items in 0-1 Knapsack by reducing weight of at most K items in half
Given weights and values of N items and the capacity W of the knapsack. Also given that the weight of at most K items can be changed to half of its original weight. The task is to find the maximum sum of values of N items that can be obtained such that the sum of weights of items in knapsack does not exceed the given capacity W. Examples: Input: W
15+ min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
Difference Between Greedy Knapsack and 0/1 Knapsack Algorithms
The 0/1 Knapsack algorithm is a dynamic programming approach where items are either completely included or not at all. It considers all combinations to find the maximum total value. On the other hand, the Greedy Knapsack algorithm, also known as the Fractional Knapsack, allows for items to be broken into fractions, selecting items with the highest
9 min read
POTD Solutions | 25 Oct’ 23 | Knapsack with Duplicate Items
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Dynamic Programming but will also help you build up problem-solving skills. We recommend you to try this
9 min read
Unbounded Knapsack (Repetition of items allowed)
Given a knapsack weight W and a set of n items with certain value vali and weight wti, we need to calculate the maximum amount that could make up this quantity exactly. This is different from classical Knapsack problem, here we are allowed to use unlimited number of instances of an item. Note: N is always positive i.e greater than zero Examples: In
15+ min read
Unbounded Knapsack (Repetition of items allowed) | Efficient Approach
Given an integer W, arrays val[] and wt[], where val[i] and wt[i] are the values and weights of the ith item, the task is to calculate the maximum value that can be obtained using weights not exceeding W. Note: Each weight can be included multiple times. Examples: Input: W = 4, val[] = {6, 18}, wt[] = {2, 3}Output: 18Explanation: The maximum value
8 min read
Printing Longest Common Subsequence | Set 2 (Printing All)
Given two sequences, print all longest subsequence present in both of them.Examples: Input: string X = "AGTGATG" string Y = "GTTAG" Output: GTAG GTTG Input: string X = "AATCC" string Y = "ACACG" Output: ACC AAC Input: string X = "ABCBDAB" string Y = "BDCABA" Output: BCAB BCBA BDAB We have discussed Longest Common Subsequence (LCS) problem here. The
12 min read
Get maximum items when other items of total cost of an item are free
Given a list of prices of 'N' items. A person can buy only one item of any price and he can get other items for free such that the total price of the rest of the items doesn't exceed the price of the bought item. The task is to find the maximum number of items the person can have. Examples: Input: n = 5, arr = {5, 3, 1, 5, 6} Output: 3 The person c
6 min read
Probability of distributing M items among X bags such that first bag contains N items
Given three integers N, M, X. The task is to find the probability of distributing M items among X bags such that first bag contains N items Examples: Input : M = 7, X =3, N = 3 Output : 0.2 The Number of ways to keep 7 items in 3 bags is [Tex]6\choose 2 [/Tex]. The Number of ways to keep 4 items in 2 bags is [Tex]3\choose 1 [/Tex]. As the first bag
5 min read
Distributing items when a person cannot take more than two items of same type
Given N sweets, which can be of many different types, and k customers, one customer won’t make the same type of sweet more than 2 pieces, the task is to find if it is possible to distribute all, then print "Yes" or otherwise "No".Given an array, arr[] represents an array of sweets. arr[i] is type of sweet. Examples: Input : arr[] = {1, 1, 2, 3, 1},
8 min read
three90RightbarBannerImg