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];
}
}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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.