Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ public static int cutRod(int[] price, int n) {
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,10 @@ void testCutRodEmptyPrices() {
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.");
}
}