Skip to content

Commit

Permalink
Fix absolute max bug (#6144)
Browse files Browse the repository at this point in the history
  • Loading branch information
rizwan-ilyas authored Jan 18, 2025
1 parent 5454e2f commit 30d0c06
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/main/java/com/thealgorithms/maths/AbsoluteMax.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static int getMaxValue(int... numbers) {
}
int absMax = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (Math.abs(numbers[i]) > Math.abs(absMax)) {
if (Math.abs(numbers[i]) > Math.abs(absMax) || (Math.abs(numbers[i]) == Math.abs(absMax) && numbers[i] > absMax)) {
absMax = numbers[i];
}
}
Expand Down
8 changes: 8 additions & 0 deletions src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,12 @@ void testGetMaxValue() {
void testGetMaxValueWithNoArguments() {
assertThrows(IllegalArgumentException.class, AbsoluteMax::getMaxValue);
}

@Test
void testGetMaxValueWithSameAbsoluteValues() {
assertEquals(5, AbsoluteMax.getMaxValue(-5, 5));
assertEquals(5, AbsoluteMax.getMaxValue(5, -5));
assertEquals(12, AbsoluteMax.getMaxValue(-12, 9, 3, 12, 1));
assertEquals(12, AbsoluteMax.getMaxValue(12, 9, 3, -12, 1));
}
}

0 comments on commit 30d0c06

Please sign in to comment.