Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[FEATURE] Iterative Solution for Unbounded 0/1 Knapsack #3091

@Kunal-notfound

Description

@Kunal-notfound

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions