Skip to content

Commit 84ce82e

Browse files
committed
Added a check for negative rod length in Rod Cutting algorithm
1 parent eaf0ea1 commit 84ce82e

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 rod length is negative
26+
if (n < 0) {
27+
throw new IllegalArgumentException("Rod length cannot be negative.");
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};
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)