{"record":{"id":"59457582662e5184","repo":"TheAlgorithms/Java","slug":"item-count-must-be-between-0-and-the-length-of-the","errorCode":null,"errorMessage":"Item count must be between 0 and the length of the values array.","messagePattern":"Item count must be between 0 and the length of the values array\\.","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java","lineNumber":47,"sourceCode":"     * @param values the values of the items\n     * @param weights the weights of the items\n     * @param capacity the total capacity of the knapsack\n     * @param itemCount the number of items\n     * @return the maximum value that can be put in the knapsack\n     * @throws IllegalArgumentException if input arrays are null, of different lengths,or if capacity or itemCount is invalid\n     */\n    public static int compute(final int[] values, final int[] weights, final int capacity, final int itemCount) {\n        if (values == null || weights == null) {\n            throw new IllegalArgumentException(\"Values and weights arrays must not be null.\");\n        }\n        if (values.length != weights.length) {\n            throw new IllegalArgumentException(\"Values and weights arrays must be non-null and of same length.\");\n        }\n        if (capacity < 0) {\n            throw new IllegalArgumentException(\"Capacity must not be negative.\");\n        }\n        if (itemCount < 0 || itemCount > values.length) {\n            throw new IllegalArgumentException(\"Item count must be between 0 and the length of the values array.\");\n        }\n\n        final int[][] dp = new int[itemCount + 1][capacity + 1];\n\n        for (int i = 1; i <= itemCount; i++) {\n            final int currentValue = values[i - 1];\n            final int currentWeight = weights[i - 1];\n\n            for (int w = 1; w <= capacity; w++) {\n                if (currentWeight <= w) {\n                    final int includeItem = currentValue + dp[i - 1][w - currentWeight];\n                    final int excludeItem = dp[i - 1][w];\n                    dp[i][w] = Math.max(includeItem, excludeItem);\n                } else {\n                    dp[i][w] = dp[i - 1][w];\n                }\n            }\n        }","sourceCodeStart":29,"sourceCodeEnd":65,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java#L29-L65","documentation":"KnapsackZeroOneTabulation.compute allocates dp[itemCount + 1][...] and indexes values[i-1] and weights[i-1] up to i = itemCount. If itemCount exceeds the array length, this causes an ArrayIndexOutOfBoundsException; if negative, a NegativeArraySizeException. The method validates 0 <= itemCount <= values.length upfront.","triggerScenarios":"Passing itemCount greater than values.length (e.g., itemCount = values.length + 1), or a negative itemCount. This happens when itemCount is computed independently from the actual array length or defaults to an incorrect value.","commonSituations":"Passing totalItems from a separate counter that drifts from the array length; itemCount = oldLength after the array was trimmed; off-by-one from using values.length instead of values.length directly.","solutions":["Pass values.length as itemCount rather than tracking a separate count.","Clamp itemCount: Math.max(0, Math.min(itemCount, values.length)).","Audit any code path that modifies the arrays independently from the count variable."],"exampleFix":"// before\nint r = KnapsackZeroOneTabulation.compute(values, weights, cap, itemCount); // throws\n\n// after\nint safeCount = Math.max(0, Math.min(itemCount, values.length));\nint r = KnapsackZeroOneTabulation.compute(values, weights, cap, safeCount);","handlingStrategy":"validation","validationCode":"if (itemCount < 0 || itemCount > values.length) {\n    throw new IllegalArgumentException(\"itemCount must be in [0, values.length]\");\n}\nint r = KnapsackZeroOneTabulation.compute(values, weights, capacity, itemCount);","typeGuard":"static boolean isValidItemCount(int itemCount, int[] values) {\n    return itemCount >= 0 && itemCount <= values.length;\n}","tryCatchPattern":null,"preventionTips":["Pass values.length as itemCount instead of maintaining a separate counter.","Clamp itemCount with Math.max(0, Math.min(itemCount, values.length))."],"tags":["knapsack","out-of-bounds","input-validation","java"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}