|
13 | 13 | * `wt` and `val` respectively, and a knapsack with a weight limit W, the task is to
|
14 | 14 | * fill the knapsack to maximize the total value.
|
15 | 15 | *
|
16 |
| - * @note weight and value of items is greater than zero. |
| 16 | + * @note weight and value of items is greater than zero |
17 | 17 | *
|
18 | 18 | * ### Algorithm
|
19 | 19 | * The approach uses dynamic programming to build a solution iteratively.
|
@@ -85,6 +85,7 @@ int KnapSackFilling(std::uint16_t i, std::uint16_t W,
|
85 | 85 | int unboundedKnapsack(std::uint16_t N, std::uint16_t W,
|
86 | 86 | const std::vector<std::uint16_t>& val,
|
87 | 87 | const std::vector<std::uint16_t>& wt) {
|
| 88 | + if(N==0)return 0; // Expect 0 since no items |
88 | 89 | std::vector<std::vector<int>> dp(N, std::vector<int>(W + 1, -1)); // Initialize memoization table
|
89 | 90 | return KnapSackFilling(N - 1, W, val, wt, dp); // Start the calculation
|
90 | 91 | }
|
@@ -122,6 +123,14 @@ static void tests() {
|
122 | 123 | // Test the function and assert the expected output
|
123 | 124 | assert(unboundedKnapsack(N3, W3, val3, wt3) == 27);
|
124 | 125 | std::cout << "Maximum Knapsack value " << unboundedKnapsack(N3, W3, val3, wt3) << std::endl;
|
| 126 | + |
| 127 | + // Test Case 4 |
| 128 | + std::uint16_t N4 = 0; // Number of items |
| 129 | + std::vector<std::uint16_t> wt4 = {}; // Weights of the items |
| 130 | + std::vector<std::uint16_t> val4 = {}; // Values of the items |
| 131 | + std::uint16_t W4 = 10; // Maximum capacity of the knapsack |
| 132 | + assert(unboundedKnapsack(N4, W4, val4, wt4) == 0); |
| 133 | + std::cout << "Maximum Knapsack value for empty arrays: " << unboundedKnapsack(N4, W4, val4, wt4) << std::endl; |
125 | 134 |
|
126 | 135 | std::cout << "All test cases passed!" << std::endl;
|
127 | 136 |
|
|
0 commit comments