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] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this 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).
Method 1: Recursion by Brute-Force algorithm OR Exhaustive Search. Approach: A simple solution is to consider all subsets of items and calculate the total weight and value of all subsets. Consider the only subsets whose total weight is smaller than W. From all such subsets, pick the maximum value subset. Optimal Sub-structure: 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.
Therefore, the maximum value that can be obtained from ‘n’ items is the max of the following two values.
Maximum value obtained by n-1 items and W weight (excluding nth item).
Value of nth item plus maximum value obtained by n-1 items and W minus the weight of the nth item (including nth item).
If the weight of ‘nth’ item is greater than ‘W’, then the nth item cannot be included and Case 1 is the only possibility.
Below is the implementation of the above approach:
C++
/* A Naive recursive implementation of
0-1 Knapsack problem */
#include <bits/stdc++.h>
usingnamespacestd;
// A utility function that returns
// maximum of two integers
intmax(inta, intb) { return(a > b) ? a : b; }
// Returns the maximum value that
// can be put in a knapsack of capacity W
intknapSack(intW, intwt[], intval[], intn)
{
// Base Case
if(n == 0 || W == 0)
return0;
// 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)
returnknapSack(W, wt, val, n - 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else
returnmax(
val[n - 1]
+ knapSack(W - wt[n - 1],
wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}
// Driver code
intmain()
{
intval[] = { 60, 100, 120 };
intwt[] = { 10, 20, 30 };
intW = 50;
intn = sizeof(val) / sizeof(val[0]);
cout << knapSack(W, wt, val, n);
return0;
}
// This code is contributed by rathbhupendra
C
/* A Naive recursive implementation
of 0-1 Knapsack problem */
#include <stdio.h>
// A utility function that returns
// maximum of two integers
intmax(inta, intb) { return(a > b) ? a : b; }
// Returns the maximum value that can be
// put in a knapsack of capacity W
intknapSack(intW, intwt[], intval[], intn)
{
// Base Case
if(n == 0 || W == 0)
return0;
// 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)
returnknapSack(W, wt, val, n - 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else
returnmax(
val[n - 1]
+ knapSack(W - wt[n - 1],
wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}
// Driver program to test above function
intmain()
{
intval[] = { 60, 100, 120 };
intwt[] = { 10, 20, 30 };
intW = 50;
intn = sizeof(val) / sizeof(val[0]);
printf("%d", knapSack(W, wt, val, n));
return0;
}
Java
/* A Naive recursive implementation
of 0-1 Knapsack problem */
classKnapsack {
// A utility function that returns
// maximum of two integers
staticintmax(inta, intb)
{
return(a > b) ? a : b;
}
// Returns the maximum value that
// can be put in a knapsack of
// capacity W
staticintknapSack(intW, intwt[], intval[], intn)
{
// Base Case
if(n == 0|| W == 0)
return0;
// 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)
returnknapSack(W, wt, val, n - 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else
returnmax(val[n - 1]
+ knapSack(W - wt[n - 1], wt,
val, n - 1),
knapSack(W, wt, val, n - 1));
}
// Driver code
publicstaticvoidmain(String args[])
{
intval[] = newint[] { 60, 100, 120};
intwt[] = newint[] { 10, 20, 30};
intW = 50;
intn = val.length;
System.out.println(knapSack(W, wt, val, n));
}
}
/*This code is contributed by Rajat Mishra */
Python
# A naive recursive implementation
# of 0-1 Knapsack Problem
# Returns the maximum value that
# can be put in a knapsack of
# capacity W
defknapSack(W, wt, val, n):
# Base Case
ifn ==0orW ==0:
return0
# 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):
returnknapSack(W, wt, val, n-1)
# return the maximum of two cases:
# (1) nth item included
# (2) not included
else:
returnmax(
val[n-1] +knapSack(
W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1))
# end of function knapSack
#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 Nikhil Kumar Singh
C#
/* A Naive recursive implementation of
0-1 Knapsack problem */
usingSystem;
classGFG {
// A utility function that returns
// maximum of two integers
staticintmax(inta, intb)
{
return(a > b) ? a : b;
}
// Returns the maximum value that can
// be put in a knapsack of capacity W
staticintknapSack(intW, int[] wt,
int[] val, intn)
{
// Base Case
if(n == 0 || W == 0)
return0;
// 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)
returnknapSack(W, wt,
val, n - 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else
returnmax(val[n - 1]
+ knapSack(W - wt[n - 1], wt,
val, n - 1),
knapSack(W, wt, val, n - 1));
}
// Driver code
publicstaticvoidMain()
{
int[] val = newint[] { 60, 100, 120 };
int[] wt = newint[] { 10, 20, 30 };
intW = 50;
intn = val.Length;
Console.WriteLine(knapSack(W, wt, val, n));
}
}
// This code is contributed by Sam007
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
functionknapSack($W, $wt, $val, $n)
{
// Base Case
if($n== 0 || $W== 0)
return0;
// 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)
returnknapSack($W, $wt, $val, $n- 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else
returnmax($val[$n- 1] +
knapSack($W- $wt[$n- 1],
$wt, $val, $n- 1),
knapSack($W, $wt, $val, $n-1));
}
// Driver Code
$val= array(60, 100, 120);
$wt= array(10, 20, 30);
$W= 50;
$n= count($val);
echoknapSack($W, $wt, $val, $n);
// This code is contributed by Sam007
?>
Javascript
<script>
/* A Naive recursive implementation of
0-1 Knapsack problem */
// A utility function that returns
// maximum of two integers
functionmax(a, b)
{
return(a > b) ? a : b;
}
// Returns the maximum value that can
// be put in a knapsack of capacity W
functionknapSack(W, wt, val, n)
{
// Base Case
if(n == 0 || W == 0)
return0;
// 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)
returnknapSack(W, wt, val, n - 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else
returnmax(val[n - 1] +
knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}
let val = [ 60, 100, 120 ];
let wt = [ 10, 20, 30 ];
let W = 50;
let n = val.length;
document.write(knapSack(W, wt, val, n));
</script>
Output
220
It should be noted that the above function computes the same sub-problems again and again. See the following recursion tree, K(1, 1) is being evaluated twice. The time complexity of this naive recursive solution is exponential (2^n).
In the following recursion tree, K() refers
to knapSack(). The two parameters indicated in the
following recursion tree are n and W.
The recursion tree is for following sample inputs.
wt[] = {1, 1, 1}, W = 2, val[] = {10, 20, 30}
K(n, W)
K(3, 2)
/ \
/ \
K(2, 2) K(2, 1)
/ \ / \
/ \ / \
K(1, 2) K(1, 1) K(1, 1) K(1, 0)
/ \ / \ / \
/ \ / \ / \
K(0, 2) K(0, 1) K(0, 1) K(0, 0) K(0, 1) K(0, 0)
Recursion tree for Knapsack capacity 2
units and 3 items of 1 unit weight.
Complexity Analysis:
Time Complexity: O(2n). As there are redundant subproblems.
Auxiliary Space :O(1) + O(N). As no extra data structure has been used for storing values but O(N) auxiliary stack space(ASS) has been used for recursion stack.
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.
Method 2: Like other typical Dynamic Programming(DP) problems, re-computation of same subproblems can be avoided by constructing a temporary array K[][] in bottom-up manner. Following is Dynamic Programming based implementation.
Approach: In the Dynamic programming we will work considering the same cases as mentioned in the recursive approach. In a DP[][] table let’s consider all the possible weights from ‘1’ to ‘W’ as the columns and weights that can be kept as the rows. The state DP[i][j] will denote maximum value of ‘j-weight’ considering all values from ‘1 to ith’. So if we consider ‘wi’ (weight in ‘ith’ row) we can fill it in all columns which have ‘weight values > wi’. Now two possibilities can take place:
Fill ‘wi’ in the given column.
Do not fill ‘wi’ in the given column.
Now we have to take a maximum of these two possibilities, formally if we do not fill ‘ith’ weight in ‘jth’ column then DP[i][j] state will be same as DP[i-1][j] but if we fill the weight, DP[i][j] will be equal to the value of ‘wi’+ value of the column weighing ‘j-wi’ in the previous row. So we take the maximum of these two possibilities to fill the current state. This visualisation will make the concept clear:
Let weight elements = {1, 2, 3}
Let weight values = {10, 15, 40}
Capacity=6
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
Explanation:
For filling 'weight = 2' we come
across 'j = 3' in which
we take maximum of
(10, 15 + DP[1][3-2]) = 25
| |
'2' '2 filled'
not filled
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
Explanation:
For filling 'weight=3',
we come across 'j=4' in which
we take maximum of (25, 40 + DP[2][4-3])
= 50
For filling 'weight=3'
we come across 'j=5' in which
we take maximum of (25, 40 + DP[2][5-3])
= 55
For filling 'weight=3'
we come across 'j=6' in which
we take maximum of (25, 40 + DP[2][6-3])
= 65
C++
// A dynamic programming based
// solution for 0-1 Knapsack problem
#include <bits/stdc++.h>
usingnamespacestd;
// A utility function that returns
// maximum of two integers
intmax(inta, intb)
{
return(a > b) ? a : b;
}
// Returns the maximum value that
// can be put in a knapsack of capacity W
intknapSack(intW, intwt[], intval[], intn)
{
inti, w;
vector<vector<int>> K(n + 1, vector<int>(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;
elseif(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];
}
}
returnK[n][W];
}
// Driver Code
intmain()
{
intval[] = { 60, 100, 120 };
intwt[] = { 10, 20, 30 };
intW = 50;
intn = sizeof(val) / sizeof(val[0]);
cout << knapSack(W, wt, val, n);
return0;
}
// This code is contributed by Debojyoti Mandal
C
// A Dynamic Programming based
// solution for 0-1 Knapsack problem
#include <stdio.h>
// A utility function that returns
// maximum of two integers
intmax(inta, intb)
{
return(a > b) ? a : b;
}
// Returns the maximum value that
// can be put in a knapsack of capacity W
intknapSack(intW, intwt[], intval[], intn)
{
inti, w;
intK[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;
elseif(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];
}
}
returnK[n][W];
}
// Driver Code
intmain()
{
intval[] = { 60, 100, 120 };
intwt[] = { 10, 20, 30 };
intW = 50;
intn = sizeof(val) / sizeof(val[0]);
printf("%d", knapSack(W, wt, val, n));
return0;
}
Java
// A Dynamic Programming based solution
// for 0-1 Knapsack problem
classKnapsack {
// A utility function that returns
// maximum of two integers
staticintmax(inta, intb)
{
return(a > b) ? a : b;
}
// Returns the maximum value that can
// be put in a knapsack of capacity W
staticintknapSack(intW, intwt[],
intval[], intn)
{
inti, w;
intK[][] = newint[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;
elseif(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];
}
}
returnK[n][W];
}
// Driver code
publicstaticvoidmain(String args[])
{
intval[] = newint[] { 60, 100, 120};
intwt[] = newint[] { 10, 20, 30};
intW = 50;
intn = val.length;
System.out.println(knapSack(W, wt, val, n));
}
}
/*This code is contributed by Rajat Mishra */
Python
# A Dynamic Programming based Python
# Program for 0-1 Knapsack problem
# Returns the maximum value that can
# be put in a knapsack of capacity W
defknapSack(W, wt, val, n):
K =[[0forx inrange(W +1)] forx inrange(n +1)]
# Build table K[][] in bottom up manner
fori inrange(n +1):
forw inrange(W +1):
ifi ==0orw ==0:
K[i][w] =0
elifwt[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]
returnK[n][W]
# Driver code
val =[60, 100, 120]
wt =[10, 20, 30]
W =50
n =len(val)
print(knapSack(W, wt, val, n))
# This code is contributed by Bhavya Jain
C#
// A Dynamic Programming based solution for
// 0-1 Knapsack problem
usingSystem;
classGFG {
// A utility function that returns
// maximum of two integers
staticintmax(inta, intb)
{
return(a > b) ? a : b;
}
// Returns the maximum value that
// can be put in a knapsack of
// capacity W
staticintknapSack(intW, int[] wt,
int[] val, intn)
{
inti, w;
int[, ] K = newint[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;
elseif(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];
}
}
returnK[n, W];
}
// Driver code
staticvoidMain()
{
int[] val = newint[] { 60, 100, 120 };
int[] wt = newint[] { 10, 20, 30 };
intW = 50;
intn = val.Length;
Console.WriteLine(knapSack(W, wt, val, n));
}
}
// This code is contributed by Sam007
PHP
<?php
// A Dynamic Programming based solution
// for 0-1 Knapsack problem
// Returns the maximum value that
// can be put in a knapsack of
// capacity W
functionknapSack($W, $wt, $val, $n)
{
$K= array(array());
// 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;
elseif($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];
}
}
return$K[$n][$W];
}
// Driver Code
$val= array(60, 100, 120);
$wt= array(10, 20, 30);
$W= 50;
$n= count($val);
echoknapSack($W, $wt, $val, $n);
// This code is contributed by Sam007.
?>
Javascript
<script>
// A Dynamic Programming based solution
// for 0-1 Knapsack problem
// A utility function that returns
// maximum of two integers
functionmax(a, b)
{
return(a > b) ? a : b;
}
// Returns the maximum value that can
// be put in a knapsack of capacity W
functionknapSack(W, wt, val, n)
{
let i, w;
let K = newArray(n + 1);
// Build table K[][] in bottom up manner
for(i = 0; i <= n; i++)
{
K[i] = newArray(W + 1);
for(w = 0; w <= W; w++)
{
if(i == 0 || w == 0)
K[i][w] = 0;
elseif(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];
}
}
returnK[n][W];
}
let val = [ 60, 100, 120 ];
let wt = [ 10, 20, 30 ];
let W = 50;
let n = val.length;
document.write(knapSack(W, wt, val, n));
</script>
Output
220
Complexity Analysis:
Time Complexity: O(N*W). where ‘N’ is the number of weight element and ‘W’ is capacity. As for every weight element we traverse through all weight capacities 1<=w<=W.
Auxiliary Space: O(N*W). The use of 2-D array of size ‘N*W’.
Scope for Improvement :- We used the same approach but with optimized space complexity
C++
#include <bits/stdc++.h>
usingnamespacestd;
// we can further improve the above Knapsack function's space
// complexity
intknapSack(intW, intwt[], intval[], intn)
{
inti, w;
intK[2][W + 1];
// We know we are always using the current row or
// the previous row of the array/vector . Thereby we can
// improve it further by using a 2D array but with only
// 2 rows i%2 will be giving the index inside the bounds
// of 2d array K
for(i = 0; i <= n; i++) {
for(w = 0; w <= W; w++) {
if(i == 0 || w == 0)
K[i % 2][w] = 0;
elseif(wt[i - 1] <= w)
K[i % 2][w] = max(
val[i - 1]
+ K[(i - 1) % 2][w - wt[i - 1]],
K[(i - 1) % 2][w]);
else
K[i % 2][w] = K[(i - 1) % 2][w];
}
}
returnK[n % 2][W];
}
// Driver Code
intmain()
{
intval[] = { 60, 100, 120 };
intwt[] = { 10, 20, 30 };
intW = 50;
intn = sizeof(val) / sizeof(val[0]);
cout << knapSack(W, wt, val, n);
return0;
}
// This code was improved by Udit Singla
Java
importjava.util.*;
classGFG {
// we can further improve the above Knapsack function's space
// complexity
staticintknapSack(intW, intwt[], intval[], intn)
{
inti, w;
int[][]K = newint[2][W + 1];
// We know we are always using the current row or
// the previous row of the array/vector . Thereby we can
// improve it further by using a 2D array but with only
// 2 rows i%2 will be giving the index inside the bounds
// of 2d array K
for(i = 0; i <= n; i++) {
for(w = 0; w <= W; w++) {
if(i == 0|| w == 0)
K[i % 2][w] = 0;
elseif(wt[i - 1] <= w)
K[i % 2][w] = Math.max(
val[i - 1]
+ K[(i - 1) % 2][w - wt[i - 1]],
K[(i - 1) % 2][w]);
else
K[i % 2][w] = K[(i - 1) % 2][w];
}
}
returnK[n % 2][W];
}
// Driver Code
publicstaticvoidmain(String[] args)
{
intval[] = { 60, 100, 120};
intwt[] = { 10, 20, 30};
intW = 50;
intn = val.length;
System.out.print(knapSack(W, wt, val, n));
}
}
// This code is contributed by gauravrajput1
Python3
# we can further improve the above Knapsack function's space
# complexity
defknapSack(W, wt, val, n):
K =[[0forx inrange(W+1)] fory inrange(2)]
# We know we are always using the current row or
# the previous row of the array/vector . Thereby we can
# improve it further by using a 2D array but with only
# 2 rows i%2 will be giving the index inside the bounds
# of 2d array K
fori inrange(n +1):
forw inrange(W +1):
if(i ==0orw ==0):
K[i %2][w] =0
elif(wt[i -1] <=w):
K[i %2][w] =max(
val[i -1]
+K[(i -1) %2][w -wt[i -1]],
K[(i -1) %2][w])
else:
K[i %2][w] =K[(i -1) %2][w]
returnK[n %2][W]
# Driver Code
if__name__ =="__main__":
val =[60, 100, 120]
wt =[10, 20, 30]
W =50
n =len(val)
print(knapSack(W, wt, val, n))
# This code is contributed by ukasp.
C#
usingSystem;
publicclassGFG {
// we can further improve the above Knapsack function's space
// the previous row of the array/vector . Thereby we can
// improve it further by using a 2D array but with only
// 2 rows i%2 will be giving the index inside the bounds
// of 2d array K
for(i = 0; i <= n; i++) {
for(w = 0; w <= W; w++) {
if(i == 0 || w == 0)
K[i % 2][w] = 0;
elseif(wt[i - 1] <= w)
K[i % 2][w] = Math.max(val[i - 1] +
K[(i - 1) % 2][w - wt[i - 1]],
K[(i - 1) % 2][w]);
else
K[i % 2][w] = K[(i - 1) % 2][w];
}
}
returnK[n % 2][W];
}
// Driver Code
varval = [ 60, 100, 120 ];
varwt = [ 10, 20, 30 ];
varW = 50;
varn = val.length;
document.write(knapSack(W, wt, val, n));
// This code is contributed by Rajput-Ji
</script>
Complexity Analysis:
Time Complexity: O(N*W).
Auxiliary Space: O(2*W) As we are using a 2-D array but with only 2 rows.
Method 3: This method uses Memoization Technique (an extension of recursive approach). This method is basically an extension to the recursive approach so that we can overcome the problem of calculating redundant cases and thus increased complexity. We can solve this problem by simply creating a 2-D array that can store a particular state (n, w) if we get it the first time. 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. This method gives an edge over the recursive approach in this aspect.
C++
// Here is the top-down approach of
// dynamic programming
#include <bits/stdc++.h>
usingnamespacestd;
// Returns the value of maximum profit
intknapSackRec(intW, intwt[],
intval[], inti,
int** dp)
{
// base condition
if(i < 0)
return0;
if(dp[i][W] != -1)
returndp[i][W];
if(wt[i] > W) {
// Store the value of function call
// stack in table before return
dp[i][W] = knapSackRec(W, wt,
val, i - 1,
dp);
returndp[i][W];
}
else{
// Store value in a table before return
dp[i][W] = max(val[i]
+ knapSackRec(W - wt[i],
wt, val,
i - 1, dp),
knapSackRec(W, wt, val,
i - 1, dp));
// Return value of table after storing
returndp[i][W];
}
}
intknapSack(intW, intwt[], intval[], intn)
{
// double pointer to declare the
// table dynamically
int** dp;
dp = newint*[n];
// loop to create the table dynamically
for(inti = 0; i < n; i++)
dp[i] = newint[W + 1];
// loop to initially filled the
// table with -1
for(inti = 0; i < n; i++)
for(intj = 0; j < W + 1; j++)
dp[i][j] = -1;
returnknapSackRec(W, wt, val, n - 1, dp);
}
// Driver Code
intmain()
{
intval[] = { 60, 100, 120 };
intwt[] = { 10, 20, 30 };
intW = 50;
intn = sizeof(val) / sizeof(val[0]);
cout << knapSack(W, wt, val, n);
return0;
}
Java
// Here is the top-down approach of
// dynamic programming
classGFG{
// A utility function that returns
// maximum of two integers
staticintmax(inta, intb)
{
return(a > b) ? a : b;
}
// Returns the value of maximum profit
staticintknapSackRec(intW, intwt[],
intval[], intn,
int[][]dp)
{
// Base condition
if(n == 0|| W == 0)
return0;
if(dp[n][W] != -1)
returndp[n][W];
if(wt[n - 1] > W)
// Store the value of function call
// stack in table before return
returndp[n][W] = knapSackRec(W, wt, val,
n - 1, dp);
else
// Return value of table after storing
returndp[n][W] = max((val[n - 1] +
knapSackRec(W - wt[n - 1], wt,
val, n - 1, dp)),
knapSackRec(W, wt, val,
n - 1, dp));
}
staticintknapSack(intW, intwt[], intval[], intN)
{
// Declare the table dynamically
intdp[][] = newint[N + 1][W + 1];
// Loop to initially filled the
// table with -1
for(inti = 0; i < N + 1; i++)
for(intj = 0; j < W + 1; j++)
dp[i][j] = -1;
returnknapSackRec(W, wt, val, N, dp);
}
// Driver Code
publicstaticvoidmain(String [] args)
{
intval[] = { 60, 100, 120};
intwt[] = { 10, 20, 30};
intW = 50;
intN = val.length;
System.out.println(knapSack(W, wt, val, N));
}
}
// This Code is contributed By FARAZ AHMAD
Python3
# This is the memoization approach of
# 0 / 1 Knapsack in Python in simple
# we can say recursion + memoization = DP
# driver code
val =[60, 100, 120]
wt =[10, 20, 30]
W =50
n =len(val)
# We initialize the matrix with -1 at first.
t =[[-1fori inrange(W +1)] forj inrange(n +1)]
defknapsack(wt, val, W, n):
# base conditions
ifn ==0orW ==0:
return0
ift[n][W] !=-1:
returnt[n][W]
# choice diagram code
ifwt[n-1] <=W:
t[n][W] =max(
val[n-1] +knapsack(
wt, val, W-wt[n-1], n-1),
knapsack(wt, val, W, n-1))
returnt[n][W]
elifwt[n-1] > W:
t[n][W] =knapsack(wt, val, W, n-1)
returnt[n][W]
print(knapsack(wt, val, W, n))
# This code is contributed by Prosun Kumar Sarkar
C#
// Here is the top-down approach of
// dynamic programming
usingSystem;
publicclassGFG
{
// A utility function that returns
// maximum of two integers
staticintmax(inta, intb) { return(a > b) ? a : b; }
Time Complexity: O(N*W). As redundant calculations of states are avoided.
Auxiliary Space: O(N*W) + O(N). The use of 2D array data structure for storing intermediate states and O(N) auxiliary stack space(ASS) has been used for recursion stack:
[Note: For 32bit integer use long instead of int.] References:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy