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 does’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 optimise 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 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 coontributed by AnkitRai01

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.MinValue;
        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 = 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++)
            Console.WriteLine (ansQuery(queries[i]));
      
      
    }
}
  
// This code is contributed by ihritik

chevron_right


Output:

11
9
3


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : AnkitRai01, ihritik