52 const std::array<int, n> &value) {
53 std::vector<std::vector<int> > maxValue(n + 1,
54 std::vector<int>(capacity + 1, 0));
57 int items =
sizeof(weight) /
sizeof(weight[0]);
58 for (
size_t i = 0; i < items + 1; ++i) {
59 for (
size_t j = 0; j < capacity + 1; ++j) {
60 if (i == 0 || j == 0) {
64 }
else if (weight[i - 1] <= j) {
72 int profit1 = value[i - 1] + maxValue[i - 1][j - weight[i - 1]];
75 int profit2 = maxValue[i - 1][j];
77 maxValue[i][j] = std::max(profit1, profit2);
81 maxValue[i][j] = maxValue[i - 1][j];
87 return maxValue[items][capacity];
99 std::array<int, n1> weight1 = {10, 20, 30};
100 std::array<int, n1> value1 = {60, 100, 120};
101 const int capacity1 = 50;
102 const int max_value1 = dynamic_programming::knapsack::maxKnapsackValue(
103 capacity1, weight1, value1);
104 const int expected_max_value1 = 220;
105 assert(max_value1 == expected_max_value1);
106 std::cout <<
"Maximum Knapsack value with " << n1 <<
" items is "
107 << max_value1 << std::endl;
111 std::array<int, n2> weight2 = {24, 10, 10, 7};
112 std::array<int, n2> value2 = {24, 18, 18, 10};
113 const int capacity2 = 25;
114 const int max_value2 = dynamic_programming::knapsack::maxKnapsackValue(
115 capacity2, weight2, value2);
116 const int expected_max_value2 = 36;
117 assert(max_value2 == expected_max_value2);
118 std::cout <<
"Maximum Knapsack value with " << n2 <<
" items is "
119 << max_value2 << std::endl;
int maxKnapsackValue(const int capacity, const std::array< int, n > &weight, const std::array< int, n > &value)
Picking up all those items whose combined weight is below the given capacity and calculating the valu...