From efb16c1eff0153ee81da7b6aafca1932f36dd722 Mon Sep 17 00:00:00 2001 From: PANKAJ PATWAL <120747214+Chiefpatwal@users.noreply.github.com> Date: Tue, 22 Oct 2024 23:20:47 +0530 Subject: [PATCH] Add edge case to handle negative rod length in RodCutting algorithm (#5904) --- .../com/thealgorithms/dynamicprogramming/RodCutting.java | 4 ++++ .../thealgorithms/dynamicprogramming/RodCuttingTest.java | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java b/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java index 76b341e2c..6d33826b6 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java @@ -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; diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/RodCuttingTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/RodCuttingTest.java index 39497a768..9cf21fd83 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/RodCuttingTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/RodCuttingTest.java @@ -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."); + } }