Knapsack 01 Dynamic Programming (Java)
Solve the 0-1 knapsack problem in Java using dynamic programming with a rolling array for space optimization.
Code
public class Knapsack {
public static int solve(int[] weights, int[] values, int capacity) {
int n = weights.length;
int[] dp = new int[capacity + 1];
for (int i = 0; i < n; i++) {
int[] next = new int[capacity + 1];
for (int w = 0; w <= capacity; w++) {
next[w] = dp[w];
if (w >= weights[i] && dp[w - weights[i]] + values[i] > next[w]) next[w] = dp[w - weights[i]] + values[i];
}
dp = next;
}
return dp[capacity];
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.