TheAlgorithms/Java · error · IllegalArgumentException
Weight capacity should not be negative.
Error message
Weight capacity should not be negative.
What it means
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.
Source
Thrown at src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java:34
* values = {60, 100, 120}
* weights = {10, 20, 30}
* W = 50
* Output: 220
*
* @author Arpita
* @see <a href="https://en.wikipedia.org/wiki/Knapsack_problem">Knapsack Problem</a>
*/
public final class Knapsack {
private Knapsack() {
}
/**
* Validates the input to ensure correct constraints.
*/
private static void throwIfInvalidInput(final int weightCapacity, final int[] weights, final int[] values) {
if (weightCapacity < 0) {
throw new IllegalArgumentException("Weight capacity should not be negative.");
}
if (weights == null || values == null || weights.length != values.length) {
throw new IllegalArgumentException("Weights and values must be non-null and of the same length.");
}
if (Arrays.stream(weights).anyMatch(w -> w <= 0)) {
throw new IllegalArgumentException("Weights must be positive.");
}
}
/**
* Solves the 0/1 Knapsack problem using Dynamic Programming (bottom-up approach).
*
* @param weightCapacity The maximum weight capacity of the knapsack.
* @param weights The array of item weights.
* @param values The array of item values.
* @return The maximum total value achievable without exceeding capacity.
*/
public static int knapSack(final int weightCapacity, final int[] weights, final int[] values) {View on GitHub (pinned to fdfb9a395b)
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.
Example fix
// before int best = Knapsack.knapSack(capacity - penalty, weights, values); // throws if penalty > capacity // after int cap = Math.max(0, capacity - penalty); int best = Knapsack.knapSack(cap, weights, values);
Defensive patterns
Strategy: validation
Validate before calling
if (weightCapacity < 0) {
throw new IllegalArgumentException("Weight capacity must be >= 0");
}
int best = Knapsack.knapSack(weightCapacity, weights, values); Type guard
static boolean isValidCapacity(int cap) {
return cap >= 0;
} Try / catch
try {
best = Knapsack.knapSack(capacity, weights, values);
} catch (IllegalArgumentException e) {
best = Knapsack.knapSack(0, weights, values); // fallback to zero capacity
} Prevention
- Replace -1 sentinel values with the actual capacity before calling.
- Clamp capacity with Math.max(0, capacity) when it comes from subtraction.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- Capacity must not be negative.
- Weights and values must be non-null and of the same length.
- Weights must be positive.
- Input arrays cannot be null.
- Value and weight arrays must be of the same length.
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/96d42e84cb4c9a02.
Report an issue: GitHub.