#include <iostream>
#include <vector>
using namespace std;
// Recursive function to find the maximum value
int knapsackRecursive(int capacity, vector<int>& weights, vector<int>& values, int n) {
// Base case: no items left or capacity becomes 0
if (n == 0 || capacity == 0) {
return 0;
}
// If the weight of the nth item is more than the capacity, skip this item
if (weights[n - 1] > capacity) {
return knapsackRecursive(capacity, weights, values, n - 1);
} else {
// Include the nth item or exclude it
int includeItem = values[n - 1] + knapsackRecursive(capacity - weights[n - 1], weights, values, n - 1);
int excludeItem = knapsackRecursive(capacity, weights, values, n - 1);
return max(includeItem, excludeItem);
}
}
int main() {
int n; // Number of items
int capacity; // Maximum weight capacity of the knapsack
// Example input
cout << "Enter number of items: ";
cin >> n;
cout << "Enter knapsack capacity: ";
cin >> capacity;
vector<int> weights(n);
vector<int> values(n);
cout << "Enter weights of items: ";
for (int i = 0; i < n; i++) {
cin >> weights[i];
}
cout << "Enter values of items: ";
for (int i = 0; i < n; i++) {
cin >> values[i];
}
int maxValue = knapsackRecursive(capacity, weights, values, n);
cout << "Maximum value in the knapsack: " << maxValue << endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKLy8gUmVjdXJzaXZlIGZ1bmN0aW9uIHRvIGZpbmQgdGhlIG1heGltdW0gdmFsdWUKaW50IGtuYXBzYWNrUmVjdXJzaXZlKGludCBjYXBhY2l0eSwgdmVjdG9yPGludD4mIHdlaWdodHMsIHZlY3RvcjxpbnQ+JiB2YWx1ZXMsIGludCBuKSB7CiAgICAvLyBCYXNlIGNhc2U6IG5vIGl0ZW1zIGxlZnQgb3IgY2FwYWNpdHkgYmVjb21lcyAwCiAgICBpZiAobiA9PSAwIHx8IGNhcGFjaXR5ID09IDApIHsKICAgICAgICByZXR1cm4gMDsKICAgIH0KCiAgICAvLyBJZiB0aGUgd2VpZ2h0IG9mIHRoZSBudGggaXRlbSBpcyBtb3JlIHRoYW4gdGhlIGNhcGFjaX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