Skip to content

Instantly share code, notes, and snippets.

@OTDE
Last active November 7, 2019 19:53
Show Gist options
  • Select an option

  • Save OTDE/0245387e1913ffb9c2239cb8809f0a4b to your computer and use it in GitHub Desktop.

Select an option

Save OTDE/0245387e1913ffb9c2239cb8809f0a4b to your computer and use it in GitHub Desktop.
Recursive implementation, with nastiness.
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