Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Knapsack {
- public static void main(String[] args) {
- int val[] = new int[]{0, 60, 100, 120};
- int wt[] = new int[]{0, 10, 20, 30};
- int W = 50;
- int n = val.length-1;
- int[][] memo = new int[n+1][W+1];
- for (int i = 0; i < memo.length; i++) {
- for (int j = 0; j < memo[i].length; j++) {
- memo[i][j] = -1;
- }
- }
- System.out.println(Knapsack.knapsack(wt, val, W, n, memo));
- }
- public static int knapsack(int[] weights, int[] values, int capacity, int index, int[][] memo) {
- if (memo[index][capacity] != -1) return memo[index][capacity];
- //base case
- if (index <= 0 || capacity <= 0) return 0;
- int result = 0;
- if (weights[index] > capacity) {
- result = knapsack(weights, values, capacity, index-1, memo);
- } else {
- int temp1 = knapsack(weights, values, capacity, index-1, memo);
- int temp2 = values[index] + knapsack(weights, values, capacity-weights[index], index-1, memo);
- result = Math.max(temp1, temp2);
- }
- memo[index][capacity] = result;
- return result;
- }
- }
Add Comment
Please, Sign In to add comment