Skip to content

Commit 122b453

Browse files
Update Unbounded_0_1_Knapsack.cpp
1 parent d7d96d7 commit 122b453

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

dynamic_programming/Unbounded_0_1_Knapsack.cpp

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
* `wt` and `val` respectively, and a knapsack with a weight limit W, the task is to
1414
* fill the knapsack to maximize the total value.
1515
*
16-
* @note weight and value of items is greater than zero.
16+
* @note weight and value of items is greater than zero
1717
*
1818
* ### Algorithm
1919
* The approach uses dynamic programming to build a solution iteratively.
@@ -85,6 +85,7 @@ int KnapSackFilling(std::uint16_t i, std::uint16_t W,
8585
int unboundedKnapsack(std::uint16_t N, std::uint16_t W,
8686
const std::vector<std::uint16_t>& val,
8787
const std::vector<std::uint16_t>& wt) {
88+
if(N==0)return 0; // Expect 0 since no items
8889
std::vector<std::vector<int>> dp(N, std::vector<int>(W + 1, -1)); // Initialize memoization table
8990
return KnapSackFilling(N - 1, W, val, wt, dp); // Start the calculation
9091
}
@@ -122,6 +123,14 @@ static void tests() {
122123
// Test the function and assert the expected output
123124
assert(unboundedKnapsack(N3, W3, val3, wt3) == 27);
124125
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;
125134

126135
std::cout << "All test cases passed!" << std::endl;
127136

0 commit comments

Comments
 (0)