Add edge case to handle negative rod length in RodCutting algorithm (#5904)

This commit is contained in:
PANKAJ PATWAL
2024-10-22 23:20:47 +05:30
committed by GitHub
parent 69a1424415
commit efb16c1eff
2 changed files with 10 additions and 0 deletions

View File

@ -22,6 +22,10 @@ public final class RodCutting {
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;

View File

@ -93,4 +93,10 @@ class RodCuttingTest {
int length = 5;
assertThrows(IllegalArgumentException.class, () -> RodCutting.cutRod(prices, length), "An empty prices array should throw an IllegalArgumentException.");
}
@Test
void testCutRodNegativeLength() {
int[] prices = {1, 5, 8, 9, 10}; // Prices are irrelevant for negative length
int length = -1;
assertThrows(IllegalArgumentException.class, () -> RodCutting.cutRod(prices, length), "A negative rod length should throw an IllegalArgumentException.");
}
}