Created
January 22, 2019 08:02
-
-
Save shahzadaazam/d07f2eb7b3b2f371bfb6824c359319fe to your computer and use it in GitHub Desktop.
Unbounded Knapsack Problem with Memoization
This file contains 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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment