Unbounded Knapsack (Repetition of items allowed) - GeeksforGeeks

20 May, 2021
Given a knapsack weight W and a set of n items with certain value vali and weight wti, we need to calculate the maximum amount that could make up this quantity exactly. This is different from classical Knapsack problem, here we are allowed to use unlimited number of instances of an item.Examples: 
Input : W = 100
       val[]  = {1, 30}
       wt[] = {1, 50}
Output : 100
There are many ways to fill knapsack.
1) 2 instances of 50 unit weight item.
2) 100 instances of 1 unit weight item.
3) 1 instance of 50 unit weight item and 50
   instances of 1 unit weight items.
We get maximum value with option 2.

Input : W = 8
       val[] = {10, 40, 50, 70}
       wt[]  = {1, 3, 4, 5}       
Output : 110 
We get maximum value with one unit of
weight 5 and one unit of weight 3.
Its an unbounded knapsack problem as we can use 1 or more instances of any resource. A simple 1D array, say dp[W+1] can be used such that dp[i] stores the maximum value which can achieved using all items and i capacity of knapsack. Note that we use 1D array here which is different from classical knapsack where we used 2D array. Here number of items never changes. We always have all items available.We can recursively compute dp[] using below formula
dp[i] = 0
dp[i] = max(dp[i], dp[i-wt[j]] + val[j] 
                   where j varies from 0 
                   to n-1 such that:
                   wt[j] <= i

result = d[W]
Below is the implementation of above idea. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum achievable value// with a knapsack of weight W and multiple// instances allowed.#include<bits/stdc++.h>using namespace std; // Returns the maximum value with knapsack of// W capacityint unboundedKnapsack(int W, int n,                       int val[], int wt[]){    // dp[i] is going to store maximum value    // with knapsack capacity i.    int dp[W+1];    memset(dp, 0, sizeof dp);     // Fill dp[] using above recursive formula    for (int i=0; i<=W; i++)      for (int j=0; j<n; j++)         if (wt[j] <= i)            dp[i] = max(dp[i], dp[i-wt[j]] + val[j]);     return dp[W];} // Driver programint main(){    int W = 100;    int val[] = {10, 30, 20};    int wt[] = {5, 10, 15};    int n = sizeof(val)/sizeof(val[0]);     cout << unboundedKnapsack(W, n, val, wt);     return 0;}
// Java program to find maximum achievable// value with a knapsack of weight W and// multiple instances allowed.public class UboundedKnapsack{         private static int max(int i, int j)    {            return (i > j) ? i : j;    }         // Returns the maximum value with knapsack    // of W capacity    private static int unboundedKnapsack(int W, int n,                                int[] val, int[] wt)    {                 // dp[i] is going to store maximum value        // with knapsack capacity i.        int dp[] = new int[W + 1];                 // Fill dp[] using above recursive formula        for(int i = 0; i <= W; i++){            for(int j = 0; j < n; j++){                if(wt[j] <= i){                    dp[i] = max(dp[i], dp[i - wt[j]] +                                val[j]);                }            }        }        return dp[W];    }     // Driver program    public static void main(String[] args)    {        int W = 100;        int val[] = {10, 30, 20};        int wt[] = {5, 10, 15};        int n = val.length;        System.out.println(unboundedKnapsack(W, n, val, wt));    }}// This code is contributed by Aditya Kumar
# Python3 program to find maximum# achievable value with a knapsack# of weight W and multiple instances allowed. # Returns the maximum value# with knapsack of W capacitydef unboundedKnapsack(W, n, val, wt):     # dp[i] is going to store maximum    # value with knapsack capacity i.    dp = [0 for i in range(W + 1)]     ans = 0     # Fill dp[] using above recursive formula    for i in range(W + 1):        for j in range(n):            if (wt[j] <= i):                dp[i] = max(dp[i], dp[i - wt[j]] + val[j])     return dp[W] # Driver programW = 100val = [10, 30, 20]wt = [5, 10, 15]n = len(val) print(unboundedKnapsack(W, n, val, wt)) # This code is contributed by Anant Agarwal.
// C# program to find maximum achievable// value with a knapsack of weight W and// multiple instances allowed.using System; class UboundedKnapsack {         private static int max(int i, int j)    {            return (i > j) ? i : j;    }         // Returns the maximum value    // with knapsack of W capacity    private static int unboundedKnapsack(int W, int n,                                  int []val, int []wt)    {                 // dp[i] is going to store maximum value        // with knapsack capacity i.        int []dp = new int[W + 1];                 // Fill dp[] using above recursive formula        for(int i = 0; i <= W; i++){            for(int j = 0; j < n; j++){                if(wt[j] <= i){                    dp[i] = Math.Max(dp[i], dp[i -                                        wt[j]] + val[j]);                }            }        }        return dp[W];    }     // Driver program    public static void Main()    {        int W = 100;        int []val = {10, 30, 20};        int []wt = {5, 10, 15};        int n = val.Length;        Console.WriteLine(unboundedKnapsack(W, n, val, wt));    }} // This code is contributed by vt_m.
<?php// PHP program to find maximum// achievable value with a// knapsack of weight W and// multiple instances allowed. // Returns the maximum value// with knapsack of W capacityfunction unboundedKnapsack($W, $n,                           $val, $wt){    // dp[i] is going to store    // maximum value with    // knapsack capacity i.    for($i = 0; $i <= $W; $i++)        $dp[$i] = 0;     $ans = 0;         // Fill dp[] using above    // recursive formula    for ($i = 0; $i <= $W; $i++)    for ($j = 0; $j < $n; $j++)        if ($wt[$j] <= $i)            $dp[$i] = max($dp[$i],                          $dp[$i - $wt[$j]] +                                   $val[$j]);     return $dp[$W];} // Driver Code$W = 100;$val = array(10, 30, 20);$wt = array(5, 10, 15);$n = count($val); //sizeof($val)/sizeof($val[0]); echo unboundedKnapsack($W, $n,                       $val, $wt); // This code is contributed// by shiv_bhakt?>
<script>    // Javascript program to find maximum achievable    // value with a knapsack of weight W and    // multiple instances allowed.         function max(i, j)    {            return (i > j) ? i : j;    }          // Returns the maximum value    // with knapsack of W capacity    function unboundedKnapsack(W, n, val, wt)    {                  // dp[i] is going to store maximum value        // with knapsack capacity i.        let dp = new Array(W + 1);        dp.fill(0);                  // Fill dp[] using above recursive formula        for(let i = 0; i <= W; i++){            for(let j = 0; j < n; j++){                if(wt[j] <= i){                    dp[i] = Math.max(dp[i], dp[i - wt[j]] + val[j]);                }            }        }        return dp[W];    }         let W = 100;    let val = [10, 30, 20];    let wt = [5, 10, 15];    let n = val.length;    document.write(unboundedKnapsack(W, n, val, wt));     </script>
Output: 
300
This article is compiled using inputs from Shubham Gupta, Shubham Joshi and Ashish kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
vt_m
Vishal_Khoda
dStudent
s_madaan25
mishrakush1999
divyesh072019
Amazon
Google
knapsack
Dynamic Programming
Amazon
Google
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Matrix Chain Multiplication | DP-8
Longest Palindromic Substring | Set 1
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Sieve of Eratosthenes
Overlapping Subproblems Property in Dynamic Programming | DP-1
Maximum size square sub-matrix with all 1s