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 = 11: select 3 + 8 = 11
If C = 10: select 9
If C = 4: select 3
Input: W[] = {1, 5, 10} q = {6, 14}
Output:
6
11
Its recommended that you go through this article on 0-1 knapsack before attempting this problem.
Naive approach: For each query, we can generate all possible subsets of weight and choose the one that has maximum weight among all those subsets that fits in the knapsack. Thus, answering each query will take exponential time.
Efficient approach: We will optimize answering each query using dynamic programming.
0-1 knapsack is solved using 2-D DP, one state 'i' for current index(i.e select or reject) and one for remaining capacity 'R'.
Recurrence relation is
dp[i][R] = max(arr[i] + dp[i + 1][R - arr[i]], dp[i + 1][R])
We will pre-compute the 2-d array dp[i][C] for every possible value of 'C' between 1 to C_MAX in O(C_MAX*i).
Using this, pre-computation we can answer each queries in O(1) time.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
#define C_MAX 30
#define max_arr_len 10
using namespace std;
// To store states of DP
int dp[max_arr_len][C_MAX + 1];
// To check if a state has
// been solved
bool v[max_arr_len][C_MAX + 1];
// Function to compute the states
int findMax(int i, int r, int w[], int n)
{
// Base case
if (r < 0)
return INT_MIN;
if (i == n)
return 0;
// Check if a state has
// been solved
if (v[i][r])
return dp[i][r];
// Setting a state as solved
v[i][r] = 1;
dp[i][r] = max(w[i] + findMax(i + 1, r - w[i], w, n),
findMax(i + 1, r, w, n));
// Returning the solved state
return dp[i][r];
}
// Function to pre-compute the states
// dp[0][0], dp[0][1], .., dp[0][C_MAX]
void preCompute(int w[], int n)
{
for (int i = C_MAX; i >= 0; i--)
findMax(0, i, w, n);
}
// Function to answer a query in O(1)
int ansQuery(int w)
{
return dp[0][w];
}
// Driver code
int main()
{
int w[] = { 3, 8, 9 };
int n = sizeof(w) / sizeof(int);
// Performing required
// pre-computation
preCompute(w, n);
int queries[] = { 11, 10, 4 };
int q = sizeof(queries) / sizeof(queries[0]);
// Perform queries
for (int i = 0; i < q; i++)
cout << ansQuery(queries[i]) << endl;
return 0;
}
Java
// Java implementation of the approach
class GFG
{
static int C_MAX = 30;
static int max_arr_len = 10;
// To store states of DP
static int dp [][] = new int [max_arr_len][C_MAX + 1];
// To check if a state has
// been solved
static boolean v[][]= new boolean [max_arr_len][C_MAX + 1];
// Function to compute the states
static int findMax(int i, int r, int w[], int n)
{
// Base case
if (r < 0)
return Integer.MIN_VALUE;
if (i == n)
return 0;
// Check if a state has
// been solved
if (v[i][r])
return dp[i][r];
// Setting a state as solved
v[i][r] = true;
dp[i][r] = Math.max(w[i] + findMax(i + 1, r - w[i], w, n),
findMax(i + 1, r, w, n));
// Returning the solved state
return dp[i][r];
}
// Function to pre-compute the states
// dp[0][0], dp[0][1], .., dp[0][C_MAX]
static void preCompute(int w[], int n)
{
for (int i = C_MAX; i >= 0; i--)
findMax(0, i, w, n);
}
// Function to answer a query in O(1)
static int ansQuery(int w)
{
return dp[0][w];
}
// Driver code
public static void main (String[] args)
{
int w[] = new int []{ 3, 8, 9 };
int n = w.length;
// Performing required
// pre-computation
preCompute(w, n);
int queries[] = new int [] { 11, 10, 4 };
int q = queries.length;
// Perform queries
for (int i = 0; i < q; i++)
System.out.println(ansQuery(queries[i]));
}
}
// This code is contributed by ihritik
Python3
# Python3 implementation of the approach
import numpy as np
import sys
C_MAX = 30
max_arr_len = 10
# To store states of DP
dp = np.zeros((max_arr_len,C_MAX + 1));
# To check if a state has
# been solved
v = np.zeros((max_arr_len,C_MAX + 1));
INT_MIN = -(sys.maxsize) + 1
# Function to compute the states
def findMax(i, r, w, n) :
# Base case
if (r < 0) :
return INT_MIN;
if (i == n) :
return 0;
# Check if a state has
# been solved
if (v[i][r]) :
return dp[i][r];
# Setting a state as solved
v[i][r] = 1;
dp[i][r] = max(w[i] + findMax(i + 1, r - w[i], w, n),
findMax(i + 1, r, w, n));
# Returning the solved state
return dp[i][r];
# Function to pre-compute the states
# dp[0][0], dp[0][1], .., dp[0][C_MAX]
def preCompute(w, n) :
for i in range(C_MAX, -1, -1) :
findMax(0, i, w, n);
# Function to answer a query in O(1)
def ansQuery(w) :
return dp[0][w];
# Driver code
if __name__ == "__main__" :
w = [ 3, 8, 9 ];
n = len(w)
# Performing required
# pre-computation
preCompute(w, n);
queries = [ 11, 10, 4 ];
q = len(queries)
# Perform queries
for i in range(q) :
print(ansQuery(queries[i]));
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
static int C_MAX = 30;
static int max_arr_len = 10;
// To store states of DP
static int[,] dp = new int [max_arr_len, C_MAX + 1];
// To check if a state has
// been solved
static bool[,] v = new bool [max_arr_len, C_MAX + 1];
// Function to compute the states
static int findMax(int i, int r, int[] w, int n)
{
// Base case
if (r < 0)
return Int32.MaxValue;
if (i == n)
return 0;
// Check if a state has
// been solved
if (v[i, r])
return dp[i, r];
// Setting a state as solved
v[i, r] = true;
dp[i, r] = Math.Max(w[i] + findMax(i + 1, r - w[i], w, n),
findMax(i + 1, r, w, n));
// Returning the solved state
return dp[i, r];
}
// Function to pre-compute the states
// dp[0][0], dp[0][1], .., dp[0][C_MAX]
static void preCompute(int[] w, int n)
{
for (int i = C_MAX; i >= 0; i--)
findMax(0, i, w, n);
}
// Function to answer a query in O(1)
static int ansQuery(int w)
{
return dp[0, w];
}
// Driver code
public static void Main()
{
int[] w= { 3, 8, 9 };
int n = w.Length;
// Performing required
// pre-computation
preCompute(w, n);
int[] queries = { 11, 10, 4 };
int q = queries.Length;
// Perform queries
for (int i = 0; i < q; i++)
Console.WriteLine(ansQuery(queries[i]));
}
}
// This code is contributed by sanjoy_62.
JavaScript
<script>
// Javascript implementation of the approach
var C_MAX = 30
var max_arr_len = 10
// To store states of DP
var dp = Array.from(Array(max_arr_len), ()=>Array(C_MAX+1));
// To check if a state has
// been solved
var v = Array.from(Array(max_arr_len), ()=>Array(C_MAX+1));
// Function to compute the states
function findMax(i, r, w, n)
{
// Base case
if (r < 0)
return -1000000000;
if (i == n)
return 0;
// Check if a state has
// been solved
if (v[i][r])
return dp[i][r];
// Setting a state as solved
v[i][r] = 1;
dp[i][r] = Math.max(w[i] + findMax(i + 1, r - w[i], w, n),
findMax(i + 1, r, w, n));
// Returning the solved state
return dp[i][r];
}
// Function to pre-compute the states
// dp[0][0], dp[0][1], .., dp[0][C_MAX]
function preCompute(w, n)
{
for (var i = C_MAX; i >= 0; i--)
findMax(0, i, w, n);
}
// Function to answer a query in O(1)
function ansQuery(w)
{
return dp[0][w];
}
// Driver code
var w = [3, 8, 9];
var n = w.length;
// Performing required
// pre-computation
preCompute(w, n);
var queries = [11, 10, 4];
var q = queries.length;
// Perform queries
for (var i = 0; i < q; i++)
document.write( ansQuery(queries[i])+ "<br>");
</script>
Efficient approach: Using DP Tabulation method ( Iterative approach )
The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.
Steps to solve this problem :
- Create a DP to store the solution of the subproblems and initialize it with 0.
- Initialize the DP with base cases
- Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP.
- After filling the DP now in Main function call every query and get the answer stored in DP.
Implementation :
C++
#include <bits/stdc++.h>
#define C_MAX 30
#define max_arr_len 10
using namespace std;
// Function to compute the maximum value that can be obtained
// from the knapsack within the given capacity
int dp[max_arr_len][C_MAX + 1] = {0};
void findMax(int w[], int n, int c)
{
// Initializing the DP table with 0
// Filling the DP table bottom-up
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= c; j++) {
if (w[i - 1] <= j) {
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - w[i - 1]] + w[i - 1]);
}
else {
dp[i][j] = dp[i - 1][j];
}
}
}
// Returning the maximum value that can be obtained
return ;
}
// Driver code
int main()
{
// Input array
int w[] = { 3, 8, 9 };
int n = sizeof(w) / sizeof(int);
// all given queries
int queries[] = { 11, 10, 4 };
int q = sizeof(queries) / sizeof(queries[0]);
// find maximum
int ma = *max_element(queries, queries + q);
// function call
findMax(w, n , ma);
// Perform queries
for (int i = 0; i < q; i++)
cout << dp[n][queries[i]] << endl;
return 0;
}
Java
public class MaxSubsetSum {
static int[][] findMax(int[] w, int n, int c) {
// Initializing the DP table with 0
int[][] dp = new int[n + 1][c + 1];
// Filling the DP table bottom-up
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= c; j++) {
if (w[i - 1] <= j) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - w[i - 1]] + w[i - 1]);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp;
}
// Driver code
public static void main(String[] args) {
int[] w = {3, 8, 9};
int n = w.length;
// All given queries
int[] queries = {11, 10, 4};
int q = queries.length;
// Find maximum
int ma = Integer.MIN_VALUE;
for (int query : queries) {
ma = Math.max(ma, query);
}
// Function call
int[][] dp = findMax(w, n, ma);
// Perform queries
for (int i = 0; i < q; i++) {
System.out.println(dp[n][queries[i]]);
}
}
}
Python3
import sys
# Function to compute the maximum value that can be obtained
# from the knapsack within the given capacity
def findMax(w, n, c):
# Initializing the DP table with 0
dp = [[0 for j in range(c + 1)] for i in range(n + 1)]
# Filling the DP table bottom-up
for i in range(1, n + 1):
for j in range(1, c + 1):
if w[i - 1] <= j:
dp[i][j] = max(dp[i - 1][j], dp[i - 1]
[j - w[i - 1]] + w[i - 1])
else:
dp[i][j] = dp[i - 1][j]
# Returning the maximum value that can be obtained
return dp
# Driver code
if __name__ == '__main__':
# Input array
w = [3, 8, 9]
n = len(w)
# all given queries
queries = [11, 10, 4]
q = len(queries)
# find maximum
ma = max(queries)
# function call
dp = findMax(w, n, ma)
# Perform queries
for i in range(q):
print(dp[n][queries[i]])
C#
using System;
public class MaxSubsetSum
{
static int[,] findMax(int[] w, int n, int c)
{
// Initializing the DP table with 0
int[,] dp = new int[n + 1, c + 1];
// Filling the DP table bottom-up
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= c; j++)
{
if (w[i - 1] <= j)
{
dp[i, j] = Math.Max(dp[i - 1, j], dp[i - 1, j - w[i - 1]] + w[i - 1]);
}
else
{
dp[i, j] = dp[i - 1, j];
}
}
}
return dp;
}
// Driver code
public static void Main(string[] args)
{
int[] w = { 3, 8, 9 };
int n = w.Length;
// All given queries
int[] queries = { 11, 10, 4 };
int q = queries.Length;
// Find maximum
int ma = int.MinValue;
foreach (int query in queries)
{
ma = Math.Max(ma, query);
}
// Function call
int[,] dp = findMax(w, n, ma);
// Perform queries
for (int i = 0; i < q; i++)
{
Console.WriteLine(dp[n, queries[i]]);
}
}
}
JavaScript
function findMax(w, n, c) {
// Initializing the DP table with 0
let dp = new Array(n + 1).fill(null).map(() => new Array(c + 1).fill(0));
// Filling the DP table bottom-up
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= c; j++) {
if (w[i - 1] <= j) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - w[i - 1]] + w[i - 1]);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
// Returning the maximum value that can be obtained
return dp;
}
// Driver code
const w = [3, 8, 9];
const n = w.length;
// all given queries
const queries = [11, 10, 4];
const q = queries.length;
// find maximum
const ma = Math.max(...queries);
// function call
const dp = findMax(w, n, ma);
// Perform queries
for (let i = 0; i < q; i++) {
console.log(dp[n][queries[i]]);
}
Time complexity: O(n*c)
Auxiliary Space: O(n*C)
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 havi
6 min read
Fractional Knapsack
0/1 Knapsack
0/1 Knapsack ProblemGiven 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 KnapsackGiven 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 solutionsGiven 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 queriesGiven 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 BoundGiven 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 put
15+ min read
0/1 Knapsack using Least Cost Branch and BoundGiven 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 SumGiven 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.Note: Each element is present in either the first subset or the second subset, but not in both.Examples: Input: arr[] = [1, 5, 11, 5]Output: true Explanation: Th
15+ min read
Count of subsets with sum equal to targetGiven 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 Ou
15+ min read
Length of longest subset consisting of A 0s and B 1s from an array of stringsGiven 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 subset
15+ min read
Breaking an Integer to get Maximum ProductGiven 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 SumGiven 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 is not possible to form the sum usi
15+ min read
Coin Change - Count Ways to Make SumGiven 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 halfGiven 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