VOOZH about

URL: https://www.geeksforgeeks.org/dsa/unbounded-knapsack-repetition-of-items-allowed-set-2/

⇱ Unbounded Knapsack (Repetition of items allowed) | Efficient Approach - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Unbounded Knapsack (Repetition of items allowed) | Efficient Approach

Last Updated : 23 Jul, 2025

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

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.


Output
300

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

Comment