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: N = 3, 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: N = 3, 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.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
// Returns the maximum value that
// can be put in a knapsack of capacity W
int knapSack(int W, vector<int>& wt, vector<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, then
// this item cannot be included
// in the optimal solution
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
return max(knapSack(W, wt, val, n - 1),
val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1));
}
// Driver code
int main() {
vector<int> profit = {60, 100, 120};
vector<int> weight = {10, 20, 30};
int W = 50;
cout << knapSack(W, weight, profit, profit.size()) << endl;
return 0;
}
C
/* A Naive recursive implementation
of 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; }
// Returns the maximum value that can be
// put in a knapsack of capacity W
int knapSack(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, then this item cannot
// be included in the optimal solution
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else
return max(
val[n - 1]
+ knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}
// Driver code
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
printf("%d", knapSack(W, weight, profit, n));
return 0;
}
Java
/* A Naive recursive implementation
of 0-1 Knapsack problem */
class GfG {
// Returns the maximum value that
// can be put in a knapsack of
// capacity W
static int knapSack(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,
// then this item cannot be included
// in the optimal solution
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else
return Math.max(knapSack(W, wt, val, n - 1),
val[n - 1] + knapSack(W - wt[n-1], wt, val, n-1));
}
// Driver code
public static void main(String args[])
{
int profit[] = new int[] { 60, 100, 120 };
int weight[] = new int[] { 10, 20, 30 };
int W = 50;
int n = profit.length;
System.out.println(knapSack(W, weight, profit, n));
}
}
Python
# A naive recursive implementation
# of 0-1 Knapsack Problem
def knapSack(W, wt, val, n):
# Base Case
if n == 0 or W == 0:
return 0
# If weight of the nth item is
# more than Knapsack of capacity W,
# then this item cannot be included
# in the optimal solution
if (wt[n-1] > W):
return knapSack(W, wt, val, n-1)
# return the maximum of two cases:
# (1) nth item included
# (2) not included
else:
return max(
val[n-1] + knapSack(
W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1))
# end of function knapSack
# Driver Code
if __name__ == '__main__':
profit = [60, 100, 120]
weight = [10, 20, 30]
W = 50
n = len(profit)
print knapSack(W, weight, profit, n)
# This code is contributed by Nikhil Kumar Singh
C#
/* A Naive recursive implementation of
0-1 Knapsack problem */
using System;
class GFG {
// Returns the maximum value that can
// be put in a knapsack of capacity W
static int knapSack(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,
// then this item cannot be
// included in the optimal solution
if (wt[n - 1] > W)
return knapSack(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]
+ knapSack(W - wt[n - 1], wt,
val, n - 1),
knapSack(W, wt, val, n - 1));
}
// Driver code
public static void Main()
{
int[] profit = new int[] { 60, 100, 120 };
int[] weight = new int[] { 10, 20, 30 };
int W = 50;
int n = profit.Length;
Console.WriteLine(knapSack(W, weight, profit, n));
}
}
// This code is contributed by Sam007
JavaScript
/* A Naive recursive implementation of
0-1 Knapsack problem */
function knapSack(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 knapSack(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]
+ knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}
let profit = [ 60, 100, 120 ];
let weight = [ 10, 20, 30 ];
let W = 50;
let n = profit.length;
console.log(knapSack(W, weight, profit, n));
PHP
<?php
// A Naive recursive implementation
// of 0-1 Knapsack problem
// Returns the maximum value that
// can be put in a knapsack of
// capacity W
function knapSack($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 knapSack($W, $wt, $val, $n - 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else
return max($val[$n - 1] +
knapSack($W - $wt[$n - 1],
$wt, $val, $n - 1),
knapSack($W, $wt, $val, $n-1));
}
// Driver Code
$profit = array(60, 100, 120);
$weight = array(10, 20, 30);
$W = 50;
$n = count($profit);
echo knapSack($W, $weight, $profit, $n);
// This code is contributed by Sam007
?>
Below is an example run of the above implementation.

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.

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 <iostream>
#include <vector>
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 kSack(int W, vector<int>& wt, vector<int>& val) {
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 << kSack(W, weight, profit) << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
// Utility function to return the maximum of two integers
int max(int a, int b) {
return (a > b) ? a : b;
}
// Returns the value of maximum profit
int kSackRec(int W, int wt[], int val[], int index, int memo[][W + 1]) {
// 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 kSack(int W, int wt[], int val[], int n) {
int memo[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
int main() {
int profit[] = {60, 100, 120};
int weight[] = {10, 20, 30};
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
printf("%d\n", kSack(W, weight, profit, n));
return 0;
}
Java
import java.util.Arrays;
public class Knapsack {
// 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 kSack(int W, int[] wt, int[] val) {
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(kSack(W, weight, profit));
}
}
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 kSack(W, wt, val):
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(kSack(W, weight, profit))
C#
using System;
class Knapsack {
// 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 kSack(int W, int[] wt, int[] val) {
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(kSack(W, weight, profit));
}
}
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 kSack(W, wt, val) {
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(kSack(W, weight, profit));
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âĢ/ | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|---|
| 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âĢ/ | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|---|
| 1 | 0 | 10 | 10 | 10 | 10 | 10 | 10 |
|---|
| 2 | | | | | | | |
|---|
| 3 | | | | | | | |
|---|
- For filling the second item:
When jthWeight = 2, then maximum possible profit is max (10, DP[1][2-2] + 15) = max(10, 15) = 15.
When jthWeight = 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âĢ/ | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|---|
| 1 | 0 | 10 | 10 | 10 | 10 | 10 | 10 |
|---|
| 2 | 0 | 10 | 15 | 25 | 25 | 25 | 25 |
|---|
| 3 | | | | | | | |
|---|
- For filling the third item:
When jthWeight = 3, the maximum possible profit is max(DP[2][3], 40+DP[2][3-3]) = max(25, 40) = 40.
When jthWeight = 4, the maximum possible profit is max(DP[2][4], 40+DP[2][4-3]) = max(25, 50) = 50.
When jthWeight = 5, the maximum possible profit is max(DP[2][5], 40+DP[2][5-3]) = max(25, 55) = 55.
When jthWeight = 6, the maximum possible profit is max(DP[2][6], 40+DP[2][6-3]) = max(25, 65) = 65.
weightâĒ itemâĢ/ | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|---|
| 1 | 0 | 10 | 10 | 10 | 10 | 10 | 10 |
|---|
| 2 | 0 | 10 | 15 | 25 | 25 | 25 | 25 |
|---|
| 3 | 0 | 10 | 15 | 40 | 50 | 55 | 65 |
|---|
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
// Returns the maximum value that
// can be put in a knapsack of capacity W
int knapSack(int W, vector<int>& wt, vector<int>& val) {
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, weight, profit) << endl;
return 0;
}
C
// A 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; }
// Returns the maximum value that
// can be put in a knapsack of capacity W
int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int dp[n + 1][W + 1]; // Renamed K to dp
// Build table dp[][] in bottom up manner
for (i = 0; i <= n; i++) {
for (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()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
printf("%d", knapSack(W, weight, profit, n));
return 0;
}
Java
// Returns the maximum value that
// can be put in a knapsack of capacity W
public class Knapsack {
public static int knapSack(int W, int[] wt, int[] val) {
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, weight, profit));
}
}
Python
# Returns the maximum value that
# can be put in a knapsack of capacity W
def knapSack(W, wt, val):
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, weight, profit))
C#
// Returns the maximum value that
// can be put in a knapsack of capacity W
using System;
using System.Collections.Generic;
class Knapsack {
public static int knapSack(int W, int[] wt, int[] val) {
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, weight, profit));
}
}
JavaScript
// Returns the maximum value that
// can be put in a knapsack of capacity W
function knapSack(W, wt, val) {
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, weight, profit));
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 <iostream>
#include <vector>
using namespace std;
// Function to find the maximum profit
int knapSack(int W, vector<int>& wt, vector<int>& val) {
// 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, weight, profit) << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
// Utility function to find the maximum of two integers
int max(int a, int b) {
return (a > b) ? a : b;
}
// Function to find the maximum profit
int knapSack(int W, int wt[], int val[], int n) {
// Making and initializing dp array
int dp[W + 1];
for (int i = 0; i <= W; i++) {
dp[i] = 0;
}
for (int i = 1; i <= n; i++) {
for (int w = W; w >= 0; w--) {
if (wt[i - 1] <= w) {
// Finding the maximum value using max function
dp[w] = max(dp[w], dp[w - wt[i - 1]] + val[i - 1]);
}
}
}
return dp[W];
}
// Driver code
int main() {
int profit[] = {60, 100, 120};
int weight[] = {10, 20, 30};
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
printf("%d\n", knapSack(W, weight, profit, n));
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG {
static int knapSack(int W, int wt[], int val[], int n)
{
// 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;
int n = profit.length;
System.out.print(knapSack(W, weight, profit, n));
}
}
Python
# Python code to implement the above approach
def knapSack(W, wt, val, n):
# 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, weight, profit, n))
C#
// Java program for the above approach
using System;
public class GFG {
static int knapSack(int W, int[] wt, int[] val, int n)
{
// 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]);
}
}
return dp[W];
}
// Driver code
public static void Main(String[] args)
{
int[] profit = { 60, 100, 120 };
int[] weight = { 10, 20, 30 };
int W = 50;
int n = profit.Length;
Console.Write(knapSack(W, weight, profit, n));
}
}
JavaScript
// Function to find the maximum profit
function knapSack(W, wt, val) {
// 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, weight, profit));
Problems based on 0-1 Knapsack
Unlock your potential with our DSA Self-Paced course, designed to help you master Data Structures and Algorithms at your own pace. In 90 days, you’ll learn the core concepts of DSA, tackle real-world problems, and boost your problem-solving skills, all at a speed that fits your schedule. With comprehensive lessons and practical exercises, this course will set you up for success in technical interviews and beyond.
And here's the challenge – join the Three 90 Challenge! Complete 90% of the course in 90 days, and you’ll earn a 90% refund. It's a great way to stay motivated, track your progress, and reward yourself for your dedication. Start the challenge today, and push your limits to achieve mastery in DSA!
Similar Reads
Introduction to Knapsack Problem, its Types and How to solve them
The Knapsack problem is an example of the combinational optimization problem. This problem is also commonly known as the "Rucksack Problem". The name of the problem is defined from the maximization problem as mentioned below: Given a bag with maximum weight capacity of W and a set of items, each hav
6 min read
Fractional Knapsack
Fractional Knapsack Problem
Given the weights and profits of N items, in the form of {profit, weight} put these items in a knapsack of capacity W to get the maximum total profit in the knapsack. In Fractional Knapsack, we can break items for maximizing the total value of the knapsack. Input: arr[] = {{60, 10}, {100, 20}, {120,
8 min read
Fractional Knapsack Queries
Given an integer array, consisting of positive weights "W" and their values "V" respectively as a pair and some queries consisting of an integer 'C' specifying the capacity of the knapsack, find the maximum value of products that can be put in the knapsack if the breaking of items is allowed. Exampl
9 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
13 min read
0/1 Knapsack
0/1 Knapsack Problem
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
15+ min read
Printing Items in 0/1 Knapsack
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 repre
12 min read
0/1 Knapsack Problem to print all possible solutions
Given weights and profits of N items, put these items in a knapsack of capacity W. The task is to print all possible solutions to the problem in such a way that there are no remaining items left whose weight is less than the remaining capacity of the knapsack. Also, compute the maximum profit.Exampl
10 min read
0-1 knapsack queries
Given an integer array W[] consisting of weights of the items and some queries consisting of capacity C of knapsack, for each query find maximum weight we can put in the knapsack. Value of C doesn't exceed a certain integer C_MAX. Examples: Input: W[] = {3, 8, 9} q = {11, 10, 4} Output: 11 9 3 If C
12 min read
0/1 Knapsack using Branch and Bound
Given two arrays v[] and w[] that represent values and weights associated with n items respectively. Find out the maximum value subset(Maximum Profit) of v[] such that the sum of the weights of this subset is smaller than or equal to Knapsack capacity W. Note: The constraint here is we can either pu
15+ min read
0/1 Knapsack using Least Cost Branch and Bound
Given N items with weights W[0..n-1], values V[0..n-1] and a knapsack with capacity C, select the items such that:Â Â The sum of weights taken into the knapsack is less than or equal to C.The sum of values of the items in the knapsack is maximum among all the possible combinations.Examples:Â Â Input:
15+ min read
Unbounded Fractional Knapsack
Given the weights and values of n items, the task is to put these items in a knapsack of capacity W to get the maximum total value in the knapsack, we can repeatedly put the same item and we can also put a fraction of an item. Examples: Input: val[] = {14, 27, 44, 19}, wt[] = {6, 7, 9, 8}, W = 50 Ou
5 min read
Unbounded Knapsack (Repetition of items allowed)
Given a knapsack weight, say capacity and a set of n items with certain value vali and weight wti, The task is to fill the knapsack in such a way that we can get the maximum profit. This is different from the classical Knapsack problem, here we are allowed to use an unlimited number of instances of
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[]
8 min read
Double Knapsack | Dynamic Programming
Given an array arr[] containing the weight of 'n' distinct items, and two knapsacks that can withstand capactiy1 and capacity2 weights, the task is to find the sum of the largest subset of the array 'arr', that can be fit in the two knapsacks. It's not allowed to break any items in two, i.e. an item
15+ min read
Some Problems of Knapsack problem
Partition a Set into Two Subsets of Equal Sum
Given an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same. Examples: Input: arr[] = [1, 5, 11, 5]Output: True Explanation: The array can be partitioned as [1, 5, 5] and [11] Input: arr[] = [1, 5, 3]Output: False Explana
15+ min read
Count of subsets with sum equal to target
Given an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target. Examples: Input: arr[] = [1, 2, 3, 3], target = 6 Output: 3 Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3] Input: arr[] = [1, 1, 1, 1], target = 1
15+ min read
Length of longest subset consisting of A 0s and B 1s from an array of strings
Given an array arr[] consisting of binary strings, and two integers a and b, the task is to find the length of the longest subset consisting of at most a 0s and b 1s. Examples: Input: arr[] = ["1" ,"0" ,"0001" ,"10" ,"111001"], a = 5, b = 3Output: 4Explanation: One possible way is to select the subs
15+ min read
Breaking an Integer to get Maximum Product
Given a number n, the task is to break n in such a way that multiplication of its parts is maximized. Input : n = 10Output: 36Explanation: 10 = 4 + 3 + 3 and 4 * 3 * 3 = 36 is the maximum possible product. Input: n = 8Output: 18Explanation: 8 = 2 + 3 + 3 and 2 * 3 * 3 = 18 is the maximum possible pr
15+ min read
Coin Change - Minimum Coins to Make Sum
Given an array of coins[] of size n and a target value sum, where coins[i] represent the coins of different denominations. You have an infinite supply of each of the coins. The task is to find the minimum number of coins required to make the given value sum. If it's not possible to make a change, re
15+ min read
Coin Change - Count Ways to Make Sum
Given an integer array of coins[] of size n representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = [1, 2, 3]Out
15+ min read
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 no
15+ min read