fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int knapsack (int W, int wt[], int val[], int n) {
  5. //Base case
  6. if (n == 0 || W == 0) {
  7. return 0;
  8. }
  9. if (wt[n-1] > W) {
  10. return knapsack(W, wt, val, n-1);
  11. } else {
  12. return max ((val[n-1] + knapsack(W-wt[n-1], wt,
  13. val, n-1)), knapsack(W, wt, val, n-1));
  14. }
  15. }
  16.  
  17. int main () {
  18. int val[] = {60, 100, 120};
  19. int wt[] = {10, 20, 30};
  20. int W = 50, n = 3;
  21. printf("%d", knapsack(W, wt, val, n));
  22. return 0;
  23. }
  24.  
Success #stdin #stdout 0s 5556KB
stdin
Standard input is empty
stdout
220