Skip to content

Instantly share code, notes, and snippets.

@RitamChakraborty
Last active July 29, 2019 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RitamChakraborty/72e9bb0fc28c97accb1432bbca492e9e to your computer and use it in GitHub Desktop.
Save RitamChakraborty/72e9bb0fc28c97accb1432bbca492e9e to your computer and use it in GitHub Desktop.
Solution for 0-1 Knapsack Problem.
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ZeroOneKnapsackProblem {
public static void main(String[] args) {
int max = 8;
int n = 4;
int[] p = {1, 2, 5, 6};
int[] w = {2, 3, 4, 5};
int[] sol = new int[n];
int[][] arr = new int[n + 1][max + 1];
IntStream.range(1, arr.length).boxed().forEach(i -> {
IntStream.range(1, arr[i].length).boxed().forEach(j -> {
if (w[i - 1] > j) {
arr[i][j] = arr[i - 1][j];
} else {
arr[i][j] = p[i - 1];
int rem = (j - w[i - 1]);
if (rem >= 0) {
arr[i][j] = Integer.max(arr[i][j], (arr[i][j] + arr[i - 1][rem]));
}
}
});
});
for (int[] a: arr) {
System.out.println(Arrays.toString(a));
}
System.out.println("");
for (int i = n; i > 0; i--) {
if (!Arrays.stream(arr[i - 1]).boxed().collect(Collectors.toList()).contains(max)) {
sol[i - 1] = 1;
max -= p[i - 1];
}
}
System.out.println("Solution: " + Arrays.toString(sol));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment