Knapsack Problem in JAVA
- oanaunciuleanu

- 22 nov. 2022
- 1 min de citit
You must introduce values into a knapsack. With n items given with weights and values, return the maximum sum of values of the subset such that the sum of weights of items is smaller or equal to the capacity of the knapsack.
Solution:
1. static int knapsack(int capacity, int[] weights, int[] values) { 2. int valuesSize = values.length; 3. int[] solutions = new int[capacity + 1]; 4. 5. for (int i = 1; i < valuesSize + 1; i++) { 6. for (int j = capacity; j >= 0; j--) { 7. if (weights[i - 1] <= j) { 8. solutions[j] = Math.max(solutions[j], 9. solutions[j - weights[i - 1]] + values[i - 1]); 10. } 11. } 12. } 13. return solutions[capacity]; 14. } 15.

Comentarii