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