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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem