TheAlgorithms/Java · error · IllegalArgumentException

Item count must be between 0 and the length of the values ar

Error message

Item count must be between 0 and the length of the values array.

What it means

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.

Source

Thrown at src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java:47

     * @param values the values of the items
     * @param weights the weights of the items
     * @param capacity the total capacity of the knapsack
     * @param itemCount the number of items
     * @return the maximum value that can be put in the knapsack
     * @throws IllegalArgumentException if input arrays are null, of different lengths,or if capacity or itemCount is invalid
     */
    public static int compute(final int[] values, final int[] weights, final int capacity, final int itemCount) {
        if (values == null || weights == null) {
            throw new IllegalArgumentException("Values and weights arrays must not be null.");
        }
        if (values.length != weights.length) {
            throw new IllegalArgumentException("Values and weights arrays must be non-null and of same length.");
        }
        if (capacity < 0) {
            throw new IllegalArgumentException("Capacity must not be negative.");
        }
        if (itemCount < 0 || itemCount > values.length) {
            throw new IllegalArgumentException("Item count must be between 0 and the length of the values array.");
        }

        final int[][] dp = new int[itemCount + 1][capacity + 1];

        for (int i = 1; i <= itemCount; i++) {
            final int currentValue = values[i - 1];
            final int currentWeight = weights[i - 1];

            for (int w = 1; w <= capacity; w++) {
                if (currentWeight <= w) {
                    final int includeItem = currentValue + dp[i - 1][w - currentWeight];
                    final int excludeItem = dp[i - 1][w];
                    dp[i][w] = Math.max(includeItem, excludeItem);
                } else {
                    dp[i][w] = dp[i - 1][w];
                }
            }
        }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass values.length as itemCount rather than tracking a separate count.
  2. Clamp itemCount: Math.max(0, Math.min(itemCount, values.length)).
  3. Audit any code path that modifies the arrays independently from the count variable.

Example fix

// before
int r = KnapsackZeroOneTabulation.compute(values, weights, cap, itemCount); // throws

// after
int safeCount = Math.max(0, Math.min(itemCount, values.length));
int r = KnapsackZeroOneTabulation.compute(values, weights, cap, safeCount);
Defensive patterns

Strategy: validation

Validate before calling

if (itemCount < 0 || itemCount > values.length) {
    throw new IllegalArgumentException("itemCount must be in [0, values.length]");
}
int r = KnapsackZeroOneTabulation.compute(values, weights, capacity, itemCount);

Type guard

static boolean isValidItemCount(int itemCount, int[] values) {
    return itemCount >= 0 && itemCount <= values.length;
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/59457582662e5184. Report an issue: GitHub.