{"record":{"id":"7e777ed90fa4070c","repo":"TheAlgorithms/Java","slug":"weights-must-be-positive","errorCode":null,"errorMessage":"Weights must be positive.","messagePattern":"Weights must be positive\\.","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java","lineNumber":40,"sourceCode":" * @see <a href=\"https://en.wikipedia.org/wiki/Knapsack_problem\">Knapsack Problem</a>\n */\npublic final class Knapsack {\n\n    private Knapsack() {\n    }\n\n    /**\n     * Validates the input to ensure correct constraints.\n     */\n    private static void throwIfInvalidInput(final int weightCapacity, final int[] weights, final int[] values) {\n        if (weightCapacity < 0) {\n            throw new IllegalArgumentException(\"Weight capacity should not be negative.\");\n        }\n        if (weights == null || values == null || weights.length != values.length) {\n            throw new IllegalArgumentException(\"Weights and values must be non-null and of the same length.\");\n        }\n        if (Arrays.stream(weights).anyMatch(w -> w <= 0)) {\n            throw new IllegalArgumentException(\"Weights must be positive.\");\n        }\n    }\n\n    /**\n     * Solves the 0/1 Knapsack problem using Dynamic Programming (bottom-up approach).\n     *\n     * @param weightCapacity The maximum weight capacity of the knapsack.\n     * @param weights        The array of item weights.\n     * @param values         The array of item values.\n     * @return The maximum total value achievable without exceeding capacity.\n     */\n    public static int knapSack(final int weightCapacity, final int[] weights, final int[] values) {\n        throwIfInvalidInput(weightCapacity, weights, values);\n\n        int[] dp = new int[weightCapacity + 1];\n\n        // Fill dp[] array iteratively\n        for (int i = 0; i < values.length; i++) {","sourceCodeStart":22,"sourceCodeEnd":58,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java#L22-L58","documentation":"The Knapsack DP requires all item weights to be strictly positive (weight > 0). A zero or negative weight breaks the DP recurrence because the inner loop indexes dp[w - currentWeight], which can go out of bounds or cause an infinite-value cell. throwIfInvalidInput scans the weights array and rejects any w <= 0.","triggerScenarios":"Passing a weights array that contains a zero or negative value — e.g., a placeholder 0 for items without a defined weight, or a negative weight from a data-entry error.","commonSituations":"Placeholder zeros in item master data; negative weights from subtracting a base offset; importing data where weight is optional and defaults to 0.","solutions":["Filter or replace any non-positive weights before calling knapSack.","Validate that every weight > 0 at data-ingestion time.","If zero-weight items are legitimate, assign them a minimum positive weight (e.g., 1) or handle them separately."],"exampleFix":"// before\nint best = Knapsack.knapSack(cap, new int[]{0, 3, 5}, values); // throws\n\n// after\nint[] weights = {0, 3, 5};\nweights = Arrays.stream(weights).map(w -> Math.max(1, w)).toArray();\nint best = Knapsack.knapSack(cap, weights, values);","handlingStrategy":"validation","validationCode":"if (Arrays.stream(weights).anyMatch(w -> w <= 0)) {\n    throw new IllegalArgumentException(\"All weights must be positive\");\n}\nint best = Knapsack.knapSack(weightCapacity, weights, values);","typeGuard":"static boolean allWeightsPositive(int[] weights) {\n    return weights != null && Arrays.stream(weights).allMatch(w -> w > 0);\n}","tryCatchPattern":null,"preventionTips":["Filter out or fix zero/negative weights at data-ingestion time.","If zero-weight items are valid for your domain, assign a minimum weight of 1 or handle them outside the knapsack."],"tags":["knapsack","non-positive-weight","input-validation","java"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}