{"record":{"id":"96d42e84cb4c9a02","repo":"TheAlgorithms/Java","slug":"weight-capacity-should-not-be-negative","errorCode":null,"errorMessage":"Weight capacity should not be negative.","messagePattern":"Weight capacity should not be negative\\.","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java","lineNumber":34,"sourceCode":" * values = {60, 100, 120}\n * weights = {10, 20, 30}\n * W = 50\n * Output: 220\n *\n * @author Arpita\n * @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) {","sourceCodeStart":16,"sourceCodeEnd":52,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java#L16-L52","documentation":"The Knapsack solver requires a non-negative weight capacity because negative capacity has no physical meaning (a knapsack cannot hold negative weight). throwIfInvalidInput checks this first and rejects weightCapacity < 0 with IllegalArgumentException before any other validation.","triggerScenarios":"Calling Knapsack.knapSack(weightCapacity, weights, values) where weightCapacity is negative — for example from a subtraction that underflows, a config typo, or a deserialized negative value.","commonSituations":"Subtracting a penalty from capacity that results in a negative number; parsing capacity from user input without clamping; defaulting capacity to -1 as a sentinel and forgetting to replace it.","solutions":["Clamp weightCapacity to zero or a positive minimum before the call.","Validate weightCapacity >= 0 at the data-ingestion boundary.","Replace any -1 sentinel with the actual capacity before invoking knapSack."],"exampleFix":"// before\nint best = Knapsack.knapSack(capacity - penalty, weights, values); // throws if penalty > capacity\n\n// after\nint cap = Math.max(0, capacity - penalty);\nint best = Knapsack.knapSack(cap, weights, values);","handlingStrategy":"validation","validationCode":"if (weightCapacity < 0) {\n    throw new IllegalArgumentException(\"Weight capacity must be >= 0\");\n}\nint best = Knapsack.knapSack(weightCapacity, weights, values);","typeGuard":"static boolean isValidCapacity(int cap) {\n    return cap >= 0;\n}","tryCatchPattern":"try {\n    best = Knapsack.knapSack(capacity, weights, values);\n} catch (IllegalArgumentException e) {\n    best = Knapsack.knapSack(0, weights, values); // fallback to zero capacity\n}","preventionTips":["Replace -1 sentinel values with the actual capacity before calling.","Clamp capacity with Math.max(0, capacity) when it comes from subtraction."],"tags":["knapsack","negative-capacity","input-validation","java"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}