Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Double Knapsack | Dynamic Programming
Next article icon

Unbounded Knapsack (Repetition of items allowed) | Efficient Approach

Last Updated : 20 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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[] = {2, 3}
Output: 18
Explanation: The maximum value that can be obtained is 18, by selecting the 2nd item once.

Input: W = 50, val[] = {6, 18}, wt[] = {2, 3}
Output: 294

Recommended Practice
Knapsack with Duplicate Items
Try It!

Naive Approach: Refer to the previous post to solve the problem using traditional Unbounded Knapsack algorithm. 

Time Complexity: O(N * W)
Auxiliary Space: O(W)

Efficient Approach:  The above approach can be optimized based on the following observations:

  • Suppose the ith index gives us the maximum value per unit weight in the given data, which can be easily found in O(n).
  • For any weight X, greater than or equal to wt[i], the maximum reachable value will be dp[X - wt[i]] + val[i].
  • We can calculate the values of dp[] from 0 to wt[i] using the traditional algorithm and we can also calculate the number of instances of ith item we can fit in W weight.
  • So the required answer will be val[i] * (W/wt[i]) + dp[W%wt[i]].
     

Below is the implementation of  new algorithm.

C++
// C++ program to implement optimized Unbounded Knapsack // algorithm #include <bits/stdc++.h> using namespace std;  // Function to implement optimized // Unbounded Knapsack algorithm int unboundedKnapsackBetter(int W, vector<int> val,                             vector<int> wt) {      // Stores most dense item     int maxDenseIndex = 0;      // Find the item with highest unit value     // (if two items have same unit value then choose the     // lighter item)     for (int i = 1; i < val.size(); i++) {         if (val[i] / wt[i]                 > val[maxDenseIndex] / wt[maxDenseIndex]             || (val[i] / wt[i]                     == val[maxDenseIndex]                            / wt[maxDenseIndex]                 && wt[i] < wt[maxDenseIndex])) {             maxDenseIndex = i;         }     }      int dp[W + 1] = { 0 };      int counter = 0;     bool breaked = false;     int i = 0;     for (i = 0; i <= W; i++) {         for (int j = 0; j < wt.size(); j++) {             if (wt[j] <= i) {                 dp[i] = max(dp[i], dp[i - wt[j]] + val[j]);             }         }         if (i - wt[maxDenseIndex] >= 0             && dp[i] - dp[i - wt[maxDenseIndex]]                    == val[maxDenseIndex]) {             counter += 1;             if (counter >= wt[maxDenseIndex]) {                 breaked = true;                 break;             }         }         else {             counter = 0;         }     }      if (!breaked) {         return dp[W];     }     else {         int start = i - wt[maxDenseIndex] + 1;         int times             = (floor)((W - start) / wt[maxDenseIndex]);         int index = (W - start) % wt[maxDenseIndex] + start;         return (times * val[maxDenseIndex] + dp[index]);     } }  // Driver Code int main() {     int W = 100;     vector<int> val = { 10, 30, 20 };     vector<int> wt = { 5, 10, 15 };     cout << unboundedKnapsackBetter(W, val, wt); }  // This code is contributed by ratiagrawal. 
Java
import java.io.*; import java.lang.*; import java.util.*;  // class to implement optimized Unbounded Knapsack algorithm class Main {      // function to implement optimized Unbounded Knapsack     // algorithm     public static int     unboundedKnapsackBetter(int W, int[] val, int[] wt)     {          // find the item with highest unit value         int maxDenseIndex = 0;         for (int i = 1; i < val.length; i++) {             if (val[i] / wt[i]                     > val[maxDenseIndex] / wt[maxDenseIndex]                 || (val[i] / wt[i]                         == val[maxDenseIndex]                                / wt[maxDenseIndex]                     && wt[i] < wt[maxDenseIndex])) {                 maxDenseIndex = i;             }         }          int[] dp = new int[W + 1];         int counter = 0;         boolean breaked = false;         int i = 0;          // dynamic programming step         for (i = 0; i <= W; i++) {             for (int j = 0; j < wt.length; j++) {                 if (wt[j] <= i) {                     dp[i] = Math.max(dp[i], dp[i - wt[j]]                                                 + val[j]);                 }             }             if (i - wt[maxDenseIndex] >= 0                 && dp[i] - dp[i - wt[maxDenseIndex]]                        == val[maxDenseIndex]) {                 counter += 1;                 if (counter >= wt[maxDenseIndex]) {                     breaked = true;                     break;                 }             }             else {                 counter = 0;             }         }          if (!breaked) {             return dp[W];         }         else {             int start = i - wt[maxDenseIndex] + 1;             int times                 = (int)((W - start) / wt[maxDenseIndex]);             int index                 = (W - start) % wt[maxDenseIndex] + start;             return (times * val[maxDenseIndex] + dp[index]);         }     }      // Driver Code     public static void main(String[] args)     {         int W = 100;         int[] val = { 10, 30, 20 };         int[] wt = { 5, 10, 15 };          System.out.println(             unboundedKnapsackBetter(W, val, wt));     } } 
Python
# Python Program to implement the above approach  from fractions import Fraction  # Function to implement optimized # Unbounded Knapsack algorithm   def unboundedKnapsackBetter(W, val, wt):      # Stores most dense item     maxDenseIndex = 0      # Find the item with highest unit value     # (if two items have same unit value then choose the lighter item)     for i in range(1, len(val)):          if Fraction(val[i], wt[i]) \             > Fraction(val[maxDenseIndex], wt[maxDenseIndex]) \             or (Fraction(val[i], wt[i]) == Fraction(val[maxDenseIndex], wt[maxDenseIndex])                 and wt[i] < wt[maxDenseIndex]):              maxDenseIndex = i      dp = [0 for i in range(W + 1)]      counter = 0     breaked = False     for i in range(W + 1):         for j in range(len(wt)):              if (wt[j] <= i):                 dp[i] = max(dp[i], dp[i - wt[j]] + val[j])          if i - wt[maxDenseIndex] >= 0 \                 and dp[i] - dp[i-wt[maxDenseIndex]] == val[maxDenseIndex]:              counter += 1              if counter >= wt[maxDenseIndex]:                  breaked = True                 # print(i)                 break         else:             counter = 0      if not breaked:         return dp[W]     else:         start = i - wt[maxDenseIndex] + 1         times = (W - start) // wt[maxDenseIndex]         index = (W - start) % wt[maxDenseIndex] + start         return (times * val[maxDenseIndex] + dp[index])   # Driver Code W = 100 val = [10, 30, 20] wt = [5, 10, 15]  print(unboundedKnapsackBetter(W, val, wt)) 
C#
// C# program to implement optimized Unbounded Knapsack // algorithm using System; public class GFG {      // function to implement optimized Unbounded Knapsack     // algorithm     static int unboundedKnapsackBetter(int W, int[] val,                                        int[] wt)     {         // find the item with highest unit value         int maxDenseIndex = 0;         for (int j = 1; j < val.Length; j++) {             if (val[j] * 1.0 / wt[j]                     > val[maxDenseIndex] * 1.0                           / wt[maxDenseIndex]                 || (val[j] * 1.0 / wt[j]                         == val[maxDenseIndex] * 1.0                                / wt[maxDenseIndex]                     && wt[j] < wt[maxDenseIndex])) {                 maxDenseIndex = j;             }         }          int[] dp = new int[W + 1];         int counter = 0;         bool breaked = false;         int x = 0;          // dynamic programming step         for (; x <= W; x++) {             for (int j = 0; j < wt.Length; j++) {                 if (wt[j] <= x) {                     dp[x] = Math.Max(dp[x], dp[x - wt[j]]                                                 + val[j]);                 }             }              if (x - wt[maxDenseIndex] >= 0                 && dp[x] - dp[x - wt[maxDenseIndex]]                        == val[maxDenseIndex]) {                 counter++;                 if (counter >= wt[maxDenseIndex]) {                     breaked = true;                     break;                 }             }             else {                 counter = 0;             }         }          if (!breaked) {             return dp[W];         }         else {             int start = x - wt[maxDenseIndex] + 1;             int times = (W - start) / wt[maxDenseIndex];             int index                 = (W - start) % wt[maxDenseIndex] + start;             return (times * val[maxDenseIndex] + dp[index]);         }     }      static public void Main()     {          // Code         int W = 100;         int[] val = { 10, 30, 20 };         int[] wt = { 5, 10, 15 };          Console.WriteLine(             unboundedKnapsackBetter(W, val, wt));     } }  // This code is contributed by karthik. 
JavaScript
// JavaScript program to implement optimized Unbounded Knapsack algorithm  // Function to implement optimized // Unbounded Knapsack algorithm function unboundedKnapsackBetter(W, val, wt) {      // Stores most dense item     let maxDenseIndex = 0      // Find the item with highest unit value     // (if two items have same unit value then choose the lighter item)     for (let i = 1; i < val.length; i++) {         if (val[i] / wt[i] > val[maxDenseIndex] / wt[maxDenseIndex]             || (val[i] / wt[i] === val[maxDenseIndex] / wt[maxDenseIndex]                 && wt[i] < wt[maxDenseIndex])) {             maxDenseIndex = i;         }     }      let dp = new Array(W + 1).fill(0);      let counter = 0;     let breaked = false;     for (var i = 0; i <= W; i++) {         for (let j = 0; j < wt.length; j++) {             if (wt[j] <= i) {                 dp[i] = Math.max(dp[i], dp[i - wt[j]] + val[j]);             }         }         if (i - wt[maxDenseIndex] >= 0 && dp[i] - dp[i - wt[maxDenseIndex]] === val[maxDenseIndex]) {             counter += 1;             if (counter >= wt[maxDenseIndex]) {                 breaked = true;                 break;             }         } else {             counter = 0;         }     }      if (!breaked) {         return dp[W];     } else {         let start = i - wt[maxDenseIndex] + 1;         let times = Math.floor((W - start) / wt[maxDenseIndex]);         let index = (W - start) % wt[maxDenseIndex] + start;         return (times * val[maxDenseIndex] + dp[index]);     } }  // Driver Code let W = 100; let val = [10, 30, 20]; let wt = [5, 10, 15]; console.log(unboundedKnapsackBetter(W, val, wt));  // This code is contributed by lokeshpotta20. 

Output
300

Time Complexity: O( N + min(wt[i], W) * N)
Auxiliary Space: O(W)


Next Article
Double Knapsack | Dynamic Programming

Z

zhangyijun396
Improve
Article Tags :
  • Dynamic Programming
  • Mathematical
  • DSA
  • knapsack
Practice Tags :
  • Dynamic Programming
  • Mathematical

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

    Fractional Knapsack Problem
    Given two arrays, val[] and wt[], representing the values and weights of items, and an integer capacity representing the maximum weight a knapsack can hold, the task is to determine the maximum total value that can be achieved by putting items in the knapsack. You are allowed to break items into fra
    8 min read
    Fractional Knapsack Queries
    Given an integer array, consisting of positive weights "W" and their values "V" respectively as a pair and some queries consisting of an integer 'C' specifying the capacity of the knapsack, find the maximum value of products that can be put in the knapsack if the breaking of items is allowed. Exampl
    9 min read
    Difference between 0/1 Knapsack problem and Fractional Knapsack problem
    What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large
    13 min read

    0/1 Knapsack

    0/1 Knapsack Problem
    Given 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 Knapsack
    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] 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 solutions
    Given 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 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 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 Bound
    Given 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 Bound
    Given 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 Sum
    Given 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 target
    Given 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 strings
    Given 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 Product
    Given 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 Sum
    Given 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 Sum
    Given 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 half
    Given 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
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
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences