Skip to content

Commit c6e01a8

Browse files
committed
Add edge case to handle negative rod length in RodCutting algorithm
1 parent e499d3b commit c6e01a8

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ public static int cutRod(int[] price, int n) {
2222
if (price == null || price.length == 0) {
2323
throw new IllegalArgumentException("Price array cannot be null or empty.");
2424
}
25+
if (n < 0) {
26+
throw new IllegalArgumentException("Rod length cannot be negative.");
27+
}
2528
// Create an array to store the maximum obtainable values for each rod length.
2629
int[] val = new int[n + 1];
2730
val[0] = 0;
@@ -40,4 +43,4 @@ public static int cutRod(int[] price, int n) {
4043
// The final element of 'val' contains the maximum obtainable value for a rod of length 'n'.
4144
return val[n];
4245
}
43-
}
46+
}

0 commit comments

Comments
 (0)