Skip to content

Commit efb16c1

Browse files
authored
Add edge case to handle negative rod length in RodCutting algorithm (#5904)
1 parent 69a1424 commit efb16c1

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ 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+
}
28+
2529
// Create an array to store the maximum obtainable values for each rod length.
2630
int[] val = new int[n + 1];
2731
val[0] = 0;

src/test/java/com/thealgorithms/dynamicprogramming/RodCuttingTest.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,10 @@ void testCutRodEmptyPrices() {
9393
int length = 5;
9494
assertThrows(IllegalArgumentException.class, () -> RodCutting.cutRod(prices, length), "An empty prices array should throw an IllegalArgumentException.");
9595
}
96+
@Test
97+
void testCutRodNegativeLength() {
98+
int[] prices = {1, 5, 8, 9, 10}; // Prices are irrelevant for negative length
99+
int length = -1;
100+
assertThrows(IllegalArgumentException.class, () -> RodCutting.cutRod(prices, length), "A negative rod length should throw an IllegalArgumentException.");
101+
}
96102
}

0 commit comments

Comments
 (0)