Last active
November 7, 2019 19:53
-
-
Save OTDE/0245387e1913ffb9c2239cb8809f0a4b to your computer and use it in GitHub Desktop.
Recursive implementation, with nastiness.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.Arrays; | |
| import java.util.List; | |
| public class Knapsack { | |
| private int[][] valueTable; | |
| private List<Item> items; | |
| int maximumValue(int capacity, List<Item> items) { | |
| valueTable = new int[items.size() + 1][capacity + 1]; | |
| this.items = items; | |
| for (int[] row: valueTable) { | |
| Arrays.fill(row, -1); | |
| } | |
| return maxValueInRange(items.size(), capacity); | |
| } | |
| private int maxValueInRange(int i, int j) { | |
| if (i == 0 || j <= 0) { | |
| return 0; | |
| } | |
| if (valueTable[i - 1][j] == -1) { | |
| valueTable[i - 1][j] = maxValueInRange(i - 1, j); | |
| } | |
| if (items.get(i - 1).weight > j) { | |
| valueTable[i][j] = valueTable[i - 1][j]; | |
| } else { | |
| if (valueTable[i - 1][j - items.get(i - 1).weight] == -1) { | |
| valueTable[i - 1][j - items.get(i - 1).weight] = | |
| maxValueInRange(i - 1, j - items.get(i - 1).weight); | |
| } | |
| valueTable[i][j] = | |
| Math.max(valueTable[i - 1][j], | |
| valueTable[i - 1][j - items.get(i - 1).weight] + | |
| items.get(i - 1).value); | |
| } | |
| return valueTable[i][j]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment