TheAlgorithms/Java · error · IllegalArgumentException

Rod length cannot be negative.

Error message

Rod length cannot be negative.

What it means

Thrown by RodCutting.cutRod(int[] price, int n) when n < 0. The rod length drives the DP array size (val = new int[n+1]); a negative n produces a negative-length array / negative indexing. Message: 'Rod length cannot be negative.'

Source

Thrown at src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java:26

    private RodCutting() {
    }

    /**
     * This method calculates the maximum obtainable value for cutting a rod of length n
     * into different pieces, given the prices for each possible piece length.
     *
     * @param price An array representing the prices of different pieces, where price[i-1]
     *              represents the price of a piece of length i.
     * @param n     The length of the rod to be cut.
     * @throws IllegalArgumentException if the price array is null or empty, or if n is less than 0.
     * @return The maximum obtainable value.
     */
    public static int cutRod(int[] price, int n) {
        if (price == null || price.length == 0) {
            throw new IllegalArgumentException("Price array cannot be null or empty.");
        }
        if (n < 0) {
            throw new IllegalArgumentException("Rod length cannot be negative.");
        }

        // Create an array to store the maximum obtainable values for each rod length.
        int[] val = new int[n + 1];
        val[0] = 0;

        // Calculate the maximum value for each rod length from 1 to n.
        for (int i = 1; i <= n; i++) {
            int maxVal = Integer.MIN_VALUE;
            // Try all possible ways to cut the rod and find the maximum value.
            for (int j = 1; j <= i; j++) {
                maxVal = Math.max(maxVal, price[j - 1] + val[i - j]);
            }
            // Store the maximum value for the current rod length.
            val[i] = maxVal;
        }

        // The final element of 'val' contains the maximum obtainable value for a rod of length 'n'.

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Clamp or reject n < 0 before the call (typically treat as 0 or error).
  2. Validate numeric input at the parse boundary with a min-value check.
  3. Unit-test the boundary (n = 0, n = 1) alongside the negative case.

Example fix

// before
int best = RodCutting.cutRod(prices, n);

// after
if (n < 0) throw new IllegalArgumentException("n must be >= 0");
int best = RodCutting.cutRod(prices, n);
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) throw new IllegalArgumentException("n must be >= 0");
RodCutting.cutRod(price, n);

Prevention

When it happens

Trigger: Passing a negative n; computing n from a subtraction that underflows; user input parsed without sign validation.

Common situations: n derived as (a - b) where b > a; CLI argument '--length=-5' accepted by a lenient parser.

Related errors


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