Knapsack 01 Dynamic Programming (Java)

Solve the 0-1 knapsack problem in Java using dynamic programming with a rolling array for space optimization.

JavaData Integrity

Code

javasnippet
15 lines
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];
    }
}

Inside the snippet

Knapsack 01 Dynamic Programming (Java) keeps everything in the class Knapsack and the function solve.

Iteration happens inside for (int i = 0; i < n; i++) — everything outside it runs once.

Putting it to use

The primary signature is public static int solve(int[] weights, int[] values, int capacity)

Core lines

return dp[capacity];

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. The file defines `solve` at load time.