fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Ideone {
  6. public static int knapsack(int[] weights, int[] values, int index, int capacity) {
  7. if (index == 0) {
  8. if (weights[0] <= capacity) return values[0];
  9. else return 0;
  10. }
  11. int notTake = knapsack(weights, values, index - 1, capacity);
  12. int take = 0;
  13. if (weights[index] <= capacity) {
  14. take = values[index] + knapsack(weights, values, index - 1, capacity - weights[index]);
  15. }
  16. return Math.max(take, notTake);
  17. }
  18. public static void main(String[] args) {
  19. int[] weights = {100, 70, 50, 10};
  20. int[] values = {10,4,6,12};
  21. int capacity = 8;
  22. int n = weights.length;
  23. int maxProfit = knapsack(weights, values, n - 1, capacity);
  24. System.out.println("Maximum Profit = " + maxProfit);
  25. }
  26. }
  27.  
Success #stdin #stdout 0.12s 55648KB
stdin
Standard input is empty
stdout
Maximum Profit = 0