-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
Description
Detailed description
The current implementation of unbounded knapsack uses recursive approach which can be improved using an iterative approach.
Context
The current recursive solution, although correct in logic, has several drawbacks:
❌ Higher memory usage due to recursive stack frames
❌ Risk of stack overflow for larger input constraints
❌ Overhead of function calls reduces performance
❌ Harder to debug and maintain
Recursive + Memoization Space Complexity --- O(N × W) + recursion stack
Iterative DP --- O(W)
where N = size of input price and weight vector
W = maximum capacity of container
Possible implementation
Replacing recursive approach with iterative solution. Iterative solution uses a bottom-up approach to build DP table.
Also raising an error if size of price and weight arrays is not equal.
Additional information
Also the Test Case - 3 provided has wrong output in assert leading to testing error
std::uint16_t N3 = 3;
std::vector<std::uint16_t> wt3 = {2, 4, 6}; // Weights of the items
std::vector<std::uint16_t> val3 = {5, 11, 13}; // Values of the items
std::uint16_t W3 = 27; // Maximum capacity of the knapsack
// Test the function and assert the expected output
assert(dynamic_programming::unbounded_knapsack::unboundedKnapsack(
N3, W3, val3, wt3) == 27); // Should be 71 instead of 27