The Wayback Machine - https://web.archive.org/web/20250308224235/https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/
Open In App

0/1 Knapsack Problem

Last Updated : 08 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. 

Note: The constraint here is we can either put an item completely into the bag or cannot put it at all [It is not possible to put a part of an item into the bag].

Input: W = 4, profit[] = [1, 2, 3], weight[] = [4, 5, 1]
Output: 3
Explanation: There are two items which have weight less than or equal to 4. If we select the item with weight 4, the possible profit is 1. And if we select the item with weight 1, the possible profit is 3. So the maximum possible profit is 3. Note that we cannot put both the items with weight 4 and 1 together as the capacity of the bag is 4.

Input: W = 3, profit[] = [1, 2, 3], weight[] = [4, 5, 6]
Output: 0

Recursion Approach – O(2n) Time and O(n) Space

To solve the problem follow the below idea:

A simple solution is to consider all subsets of items and calculate the total weight and profit of all subsets. Consider the only subsets whose total weight is smaller than W. From all such subsets, pick the subset with maximum profit.

Optimal Substructure: To consider all subsets of items, there can be two cases for every item. 

  • Case 1: The item is included in the optimal subset.
  • Case 2: The item is not included in the optimal set.

Follow the below steps to solve the problem:

The maximum value obtained from ‘n’ items is the max of the following two values. 

  • Case 1 (include the nth item): Value of the nth item plus maximum value obtained by remaining n-1 items and remaining weight i.e. (W-weight of the nth item).
  • Case 2 (exclude the nth item): Maximum value obtained by n-1 items and W weight.
  • If the weight of the ‘nth‘ item is greater than ‘W’, then the nth item cannot be included and Case 2 is the only possibility.
C++
#include <bits/stdc++.h>
using namespace std;
// Returns the maximum value that
// can be put in a knapsack of capacity W
int knapSackRec(int W, vector<int> &wt, vector<int> &val, int n)
{

    // Base Case
    if (n == 0 || W == 0)
        return 0;

    if (wt[n - 1] > W)
        return knapSackRec(W, wt, val, n - 1);

    return max(knapSackRec(W, wt, val, n - 1), val[n - 1] + knapSackRec(W - wt[n - 1], wt, val, n - 1));
}

int knapSack(int W, vector<int> &val, vector<int> &wt)
{
    int n = val.size();
    return knapSackRec(W, wt, val, n);
}
// Driver code
int main()
{
    vector<int> profit = {60, 100, 120};
    vector<int> weight = {10, 20, 30};
    int W = 50;

    cout << knapSack(W, profit, weight) << endl;
    return 0;
}
Java
import java.util.*;

class GfG {
    // Returns the maximum value that can be put in a
    // knapsack of capacity W
    static int knapSackRec(int W, int[] wt, int[] val,
                           int n)
    {
        // Base Case
        if (n == 0 || W == 0)
            return 0;

        // If weight of the nth item is more than Knapsack
        // capacity W, exclude it
        if (wt[n - 1] > W)
            return knapSackRec(W, wt, val, n - 1);

        // Return the maximum of two cases:
        // (1) nth item included
        // (2) not included
        return Math.max(knapSackRec(W, wt, val, n - 1),
                        val[n - 1]
                            + knapSackRec(W - wt[n - 1], wt,
                                          val, n - 1));
    }

    static int knapSack(int W, int[] val, int[] wt)
    {
        int n = val.length;
        return knapSackRec(W, wt, val, n);
    }
    // Driver code
    public static void main(String[] args)
    {
        int[] profit = { 60, 100, 120 };
        int[] weight = { 10, 20, 30 };
        int W = 50;

        System.out.println(knapSack(W, profit, weight));
    }
}
Python
# A naive recursive implementation of 0-1 Knapsack Problem

def knapSackRec(W, val, wt, n):
    # Base Case
    if n == 0 or W == 0:
        return 0

    # If weight of the nth item is more than Knapsack capacity W, exclude it
    if wt[n - 1] > W:
        return knapSackRec(W, val, wt, n - 1)

    # Return the maximum of two cases:
    # (1) nth item included
    # (2) not included
    return max(
        val[n - 1] + knapSackRec(W - wt[n - 1], val, wt, n - 1),
        knapSackRec(W, val, wt, n - 1)
    )

# Function to initialize the recursive call


def knapSack(W, val, wt):
    n = len(val)
    return knapSackRec(W, val, wt, n)


# Driver Code
if __name__ == '__main__':
    profit = [60, 100, 120]
    weight = [10, 20, 30]
    W = 50

    print(knapSack(W, profit, weight))
C#
using System;

class GfG {

    // Returns the maximum value that can be put in a
    // knapsack of capacity W
    static int knapSackRec(int W, int[] wt, int[] val,
                           int n)
    {
        // Base Case
        if (n == 0 || W == 0)
            return 0;

        // If weight of the nth item is more than Knapsack
        // capacity W, exclude it
        if (wt[n - 1] > W)
            return knapSackRec(W, wt, val, n - 1);

        // Return the maximum of two cases:
        // (1) nth item included
        // (2) not included
        return Math.Max(val[n - 1]
                            + knapSackRec(W - wt[n - 1], wt,
                                          val, n - 1),
                        knapSackRec(W, wt, val, n - 1));
    }

    static int knapSack(int W, int[] val, int[] wt)
    {

        int n = val.Length;
        return knapSackRec(W, wt, val, n);
    }
    // Driver code
    public static void Main()
    {
        int[] profit = { 60, 100, 120 };
        int[] weight = { 10, 20, 30 };
        int W = 50;

        Console.WriteLine(knapSack(W, profit, weight));
    }
}
JavaScript
/* A Naive recursive implementation of
    0-1 Knapsack problem */
function knapSackRec(W, wt, val, n)
{
    // Base Case
    if (n == 0 || W == 0)
        return 0;

    // If weight of the nth item is
    // more than Knapsack capacity W,
    // then this item cannot be
    // included in the optimal solution
    if (wt[n - 1] > W)
        return knapSackRec(W, wt, val, n - 1);

    // Return the maximum of two cases:
    // (1) nth item included
    // (2) not included
    else
        return Math.max(val[n - 1]
                            + knapSackRec(W - wt[n - 1], wt,
                                          val, n - 1),
                        knapSackRec(W, wt, val, n - 1));
}

function knapSack(W, val, wt)
{
    let n = val.length;
    return knapSackRec(W, wt, val, n);
}
let profit = [ 60, 100, 120 ];
let weight = [ 10, 20, 30 ];
let W = 50;

console.log(knapSack(W, profit, weight));

Output
220

Below is an example run of the above implementation.

Recursion-Tree-for-01-KnapSack

Memoization Approach – O(n x W) Time and Space

Note: The above function using recursion computes the same subproblems again and again. See the following recursion tree, K(1, 1) is being evaluated twice.

Recursion-tree-for-01-Knapsack

As there are repetitions of the same subproblem again and again we can implement the following idea to solve the problem.

If we get a subproblem the first time, we can solve this problem by creating a 2-D array that can store a particular state (n, w). Now if we come across the same state (n, w) again instead of calculating it in exponential complexity we can directly return its result stored in the table in constant time.

C++
#include <bits/stdc++.h>
using namespace std;

// Returns the value of maximum profit
int kSackRec(int W, vector<int> &wt, vector<int> &val, int index, vector<vector<int>> &memo)
{

    // Base condition
    if (index < 0)
        return 0;

    if (memo[index][W] != -1)
        return memo[index][W];

    // Store the value in the table before return
    if (wt[index] > W)
    {
        memo[index][W] = kSackRec(W, wt, val, index - 1, memo);
    }
    else
    {
        memo[index][W] = max(val[index] + kSackRec(W - wt[index], wt, val, index - 1, memo),
                             kSackRec(W, wt, val, index - 1, memo));
    }

    return memo[index][W];
}

int knapSack(int W, vector<int> &val, vector<int> &wt)
{
    int n = wt.size();
    vector<vector<int>> memo(n, vector<int>(W + 1, -1));
    return kSackRec(W, wt, val, n - 1, memo);
}

// Driver Code
int main()
{
    vector<int> profit = {60, 100, 120};
    vector<int> weight = {10, 20, 30};
    int W = 50;
    cout << knapSack(W, profit, weight) << endl;
    return 0;
}
Java
import java.util.Arrays;

class GfG {

    // Returns the value of maximum profit
    public static int kSackRec(int W, int[] wt, int[] val,
                               int index, int[][] memo)
    {

        // Base condition
        if (index < 0)
            return 0;

        if (memo[index][W] != -1)
            return memo[index][W];

        // Store the value in the table before return
        if (wt[index] > W) {
            memo[index][W]
                = kSackRec(W, wt, val, index - 1, memo);
        }
        else {
            memo[index][W] = Math.max(
                val[index]
                    + kSackRec(W - wt[index], wt, val,
                               index - 1, memo),
                kSackRec(W, wt, val, index - 1, memo));
        }

        return memo[index][W];
    }

    public static int knapSack(int W, int[] val, int[] wt)
    {
        int n = wt.length;
        int[][] memo = new int[n][W + 1];
        for (int[] row : memo) {
            Arrays.fill(row, -1);
        }
        return kSackRec(W, wt, val, n - 1, memo);
    }

    // Driver Code
    public static void main(String[] args)
    {
        int[] profit = { 60, 100, 120 };
        int[] weight = { 10, 20, 30 };
        int W = 50;
        System.out.println(knapSack(W, profit, weight));
    }
}
Python
def kSackRec(W, wt, val, index, memo):
    # Base condition
    if index < 0:
        return 0

    if memo[index][W] != -1:
        return memo[index][W]

    # Store the value in the table before return
    if wt[index] > W:
        memo[index][W] = kSackRec(W, wt, val, index - 1, memo)
    else:
        memo[index][W] = max(val[index] + kSackRec(W - wt[index], wt, val, index - 1, memo),
                             kSackRec(W, wt, val, index - 1, memo))

    return memo[index][W]


def knapSack(W, val, wt):
    n = len(wt)
    memo = [[-1 for _ in range(W + 1)] for _ in range(n)]
    return kSackRec(W, wt, val, n - 1, memo)


# Driver Code
profit = [60, 100, 120]
weight = [10, 20, 30]
W = 50
print(knapSack(W, profit, weight))
C#
using System;

class GfG {

    // Returns the value of maximum profit
    static int kSackRec(int W, int[] wt, int[] val,
                        int index, int[, ] memo)
    {

        // Base condition
        if (index < 0)
            return 0;

        if (memo[index, W] != -1)
            return memo[index, W];

        // Store the value in the table before return
        if (wt[index] > W) {
            memo[index, W]
                = kSackRec(W, wt, val, index - 1, memo);
        }
        else {
            memo[index, W] = Math.Max(
                val[index]
                    + kSackRec(W - wt[index], wt, val,
                               index - 1, memo),
                kSackRec(W, wt, val, index - 1, memo));
        }

        return memo[index, W];
    }

    public static int knapSack(int W, int[] val, int[] wt)
    {
        int n = wt.Length;
        int[, ] memo = new int[n, W + 1];
        for (int i = 0; i < n; i++)
            for (int j = 0; j <= W; j++)
                memo[i, j] = -1;
        return kSackRec(W, wt, val, n - 1, memo);
    }

    // Driver Code
    public static void Main()
    {
        int[] profit = { 60, 100, 120 };
        int[] weight = { 10, 20, 30 };
        int W = 50;
        Console.WriteLine(knapSack(W, profit, weight));
    }
}
JavaScript
function kSackRec(W, wt, val, index, memo)
{
    // Base condition
    if (index < 0)
        return 0;

    if (memo[index][W] !== -1)
        return memo[index][W];

    // Store the value in the table before return
    if (wt[index] > W) {
        memo[index][W]
            = kSackRec(W, wt, val, index - 1, memo);
    }
    else {
        memo[index][W] = Math.max(
            val[index]
                + kSackRec(W - wt[index], wt, val,
                           index - 1, memo),
            kSackRec(W, wt, val, index - 1, memo));
    }

    return memo[index][W];
}

function knapSack(W, val, wt)
{
    const n = wt.length;
    const memo = Array.from({length : n},
                            () => Array(W + 1).fill(-1));
    return kSackRec(W, wt, val, n - 1, memo);
}

// Driver Code
const profit = [ 60, 100, 120 ];
const weight = [ 10, 20, 30 ];
const W = 50;
console.log(knapSack(W, profit, weight));

Output
220

Tabulation or Bottom-Up Approach – O(n x W) Time and Space

Since subproblems are evaluated again, this problem has Overlapping Sub-problems property. So the 0/1 Knapsack problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computation of the same subproblems can be avoided by constructing a temporary array K[][] in a bottom-up manner. 

Illustration:

Below is the illustration of the above approach:

Let, weight[] = [1, 2, 3], profit[] = [10, 15, 40], Capacity = 6

  • If no element is filled, then the possible profit is 0.
weight⇢
item⇣/
0123456
00000000
1       
2       
3       
  • For filling the first item in the bag: If we follow the above mentioned procedure, the table will look like the following.
weight⇢
item⇣/
0123456
00000000
10101010101010
2       
3       
  • For filling the second item:  
    When jth Weight = 2, then maximum possible profit is max (10, DP[1][2-2] + 15) = max(10, 15) = 15.
    When jth Weight = 3, then maximum possible profit is  max(2 not put, 2 is put into bag) = max(DP[1][3], 15+DP[1][3-2]) = max(10, 25) = 25.
weight⇢
item⇣/
0123456
00000000
10101010101010
20101525252525
3       
  • For filling the third item:
    When jth Weight = 3, the maximum possible profit is max(DP[2][3], 40+DP[2][3-3]) = max(25, 40) = 40.
    When jth Weight = 4, the maximum possible profit is max(DP[2][4], 40+DP[2][4-3]) = max(25, 50) = 50.
    When jth Weight = 5, the maximum possible profit is max(DP[2][5], 40+DP[2][5-3]) = max(25, 55) = 55.
    When jth Weight = 6, the maximum possible profit is max(DP[2][6], 40+DP[2][6-3]) = max(25, 65) = 65.
weight⇢
item⇣/
0123456
00000000
10101010101010
20101525252525
30101540505565
C++
#include <bits/stdc++.h>
using namespace std;

// Returns the maximum value that
// can be put in a knapsack of capacity W
int knapSack(int W, vector<int> &val, vector<int> &wt)
{
    int n = wt.size();
    vector<vector<int>> dp(n + 1, vector<int>(W + 1));

    // Build table dp[][] in bottom-up manner
    for (int i = 0; i <= n; i++)
    {
        for (int w = 0; w <= W; w++)
        {
            if (i == 0 || w == 0)
                dp[i][w] = 0;
            else if (wt[i - 1] <= w)
                dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]);
            else
                dp[i][w] = dp[i - 1][w];
        }
    }
    return dp[n][W];
}

// Driver Code
int main()
{
    vector<int> profit = {60, 100, 120};
    vector<int> weight = {10, 20, 30};
    int W = 50;
    cout << knapSack(W, profit, weight) << endl;

    return 0;
}
Java
// Returns the maximum value that
// can be put in a knapsack of capacity W
class GfG {
    public static int knapSack(int W, int[] val, int[] wt)
    {
        int n = wt.length;
        int[][] dp = new int[n + 1][W + 1];

        // Build table dp[][] in bottom-up manner
        for (int i = 0; i <= n; i++) {
            for (int w = 0; w <= W; w++) {
                if (i == 0 || w == 0)
                    dp[i][w] = 0;
                else if (wt[i - 1] <= w)
                    dp[i][w] = Math.max(
                        val[i - 1]
                            + dp[i - 1][w - wt[i - 1]],
                        dp[i - 1][w]);
                else
                    dp[i][w] = dp[i - 1][w];
            }
        }
        return dp[n][W];
    }

    // Driver Code
    public static void main(String[] args)
    {
        int[] profit = { 60, 100, 120 };
        int[] weight = { 10, 20, 30 };
        int W = 50;

        System.out.println(knapSack(W, profit, weight));
    }
}
Python
# Returns the maximum value that
# can be put in a knapsack of capacity W
def knapSack(W, val, wt):
    n = len(wt)
    dp = [[0 for _ in range(W + 1)] for _ in range(n + 1)]

    # Build table dp[][] in bottom-up manner
    for i in range(n + 1):
        for w in range(W + 1):
            if i == 0 or w == 0:
                dp[i][w] = 0
            elif wt[i - 1] <= w:
                dp[i][w] = max(val[i - 1] + dp[i - 1]
                               [w - wt[i - 1]], dp[i - 1][w])
            else:
                dp[i][w] = dp[i - 1][w]
    return dp[n][W]


# Driver Code
profit = [60, 100, 120]
weight = [10, 20, 30]
W = 50

print(knapSack(W, profit, weight))
C#
// Returns the maximum value that
// can be put in a knapsack of capacity W
using System;
using System.Collections.Generic;

class GfG {
    public static int knapSack(int W, int[] val, int[] wt)
    {
        int n = wt.Length;
        int[, ] dp = new int[n + 1, W + 1];

        // Build table dp[][] in bottom-up manner
        for (int i = 0; i <= n; i++) {
            for (int w = 0; w <= W; w++) {
                if (i == 0 || w == 0)
                    dp[i, w] = 0;
                else if (wt[i - 1] <= w)
                    dp[i, w] = Math.Max(
                        val[i - 1]
                            + dp[i - 1, w - wt[i - 1]],
                        dp[i - 1, w]);
                else
                    dp[i, w] = dp[i - 1, w];
            }
        }
        return dp[n, W];
    }

    // Driver Code
    public static void Main()
    {
        int[] profit = { 60, 100, 120 };
        int[] weight = { 10, 20, 30 };
        int W = 50;

        Console.WriteLine(knapSack(W, profit, weight));
    }
}
JavaScript
// Returns the maximum value that
// can be put in a knapsack of capacity W
function knapSack(W, val, wt)
{
    let n = wt.length;
    let dp = Array.from({length : n + 1},
                        () => Array(W + 1).fill(0));

    // Build table dp[][] in bottom-up manner
    for (let i = 0; i <= n; i++) {
        for (let w = 0; w <= W; w++) {
            if (i === 0 || w === 0)
                dp[i][w] = 0;
            else if (wt[i - 1] <= w)
                dp[i][w] = Math.max(
                    val[i - 1] + dp[i - 1][w - wt[i - 1]],
                    dp[i - 1][w]);
            else
                dp[i][w] = dp[i - 1][w];
        }
    }
    return dp[n][W];
}

// Driver Code
let profit = [ 60, 100, 120 ];
let weight = [ 10, 20, 30 ];
let W = 50;

console.log(knapSack(W, profit, weight));

Output
220

Space optimized Approach – O(n x W) Time and O(W) Space

For calculating the current row of the dp[] array we require only previous row, but if we start traversing the rows from right to left then it can be done with a single row only

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the maximum profit
int knapSack(int W, vector<int> &val, vector<int> &wt)
{

    // Making and initializing dp vector
    vector<int> dp(W + 1, 0);

    for (int i = 1; i <= wt.size(); i++)
    {
        for (int w = W; w >= 0; w--)
        {
            if (wt[i - 1] <= w)

                // Finding the maximum value
                dp[w] = max(dp[w], dp[w - wt[i - 1]] + val[i - 1]);
        }
    }
    return dp[W];
}

// Driver code
int main()
{
    vector<int> profit = {60, 100, 120};
    vector<int> weight = {10, 20, 30};
    int W = 50;
    cout << knapSack(W, profit, weight) << endl;
    return 0;
}
Java
// Java program for the above approach

import java.util.*;

class GfG {
    static int knapSack(int W, int val[], int wt[])
    {
        int n = val.length;
        // Making and initializing dp array
        int[] dp = new int[W + 1];

        for (int i = 1; i < n + 1; i++) {
            for (int w = W; w >= 0; w--) {

                if (wt[i - 1] <= w)

                    // Finding the maximum value
                    dp[w]
                        = Math.max(dp[w], dp[w - wt[i - 1]]
                                              + val[i - 1]);
            }
        }
        // Returning the maximum value of knapsack
        return dp[W];
    }

    // Driver code
    public static void main(String[] args)
    {
        int profit[] = { 60, 100, 120 };
        int weight[] = { 10, 20, 30 };
        int W = 50;
        System.out.print(knapSack(W, profit, weight));
    }
}
Python
# Python code to implement the above approach


def knapSack(W, val, wt):

    # Making the dp array
    dp = [0 for i in range(W + 1)]

    # Taking first i elements
    for i in range(1, n + 1):

        # Starting from back,
        # so that we also have data of
        # previous computation when taking i-1 items
        for w in range(W, 0, -1):
            if wt[i - 1] <= w:

                # Finding the maximum value
                dp[w] = max(dp[w], dp[w - wt[i - 1]] + val[i - 1])

    return dp[W]


# Driver code
if __name__ == '__main__':
    profit = [60, 100, 120]
    weight = [10, 20, 30]
    W = 50
    n = len(profit)
    print(knapSack(W, profit, weight))
C#
// Java program for the above approach

using System;
public class GfG {
    static int knapSack(int W, int[] val, int[] wt)
    {
        // Making and initializing dp array
        int n = val.Length;
        int[] dp = new int[W + 1];

        for (int i = 1; i < n + 1; i++) {
            for (int w = W; w >= 0; w--) {

                if (wt[i - 1] <= w)

                    // Finding the maximum value
                    dp[w]
                        = Math.Max(dp[w], dp[w - wt[i - 1]]
                                              + val[i - 1]);
            }
        }
        return dp[W];
    }

    // Driver code
    public static void Main(String[] args)
    {
        int[] profit = { 60, 100, 120 };
        int[] weight = { 10, 20, 30 };
        int W = 50;
        Console.Write(knapSack(W, profit, weight));
    }
}
JavaScript
// Function to find the maximum profit
function knapSack(W, val, wt)
{

    // Making and initializing dp array
    let dp = new Array(W + 1).fill(0);

    for (let i = 1; i <= wt.length; i++) {
        for (let w = W; w >= 0; w--) {
            if (wt[i - 1] <= w) {

                // Finding the maximum value
                dp[w] = Math.max(dp[w], dp[w - wt[i - 1]]
                                            + val[i - 1]);
            }
        }
    }
    return dp[W];
}

// Driver code
const profit = [ 60, 100, 120 ];
const weight = [ 10, 20, 30 ];
const W = 50;

console.log(knapSack(W, profit, weight));

Output
220

Problems based on 0-1 Knapsack



Next Article

Similar Reads

three90RightbarBannerImg