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