Fix absolute max bug (#6144)

This commit is contained in:
Muhammad Rizwan
2025-01-19 00:51:56 +05:00
committed by GitHub
parent 5454e2ff62
commit 30d0c064a7
2 changed files with 9 additions and 1 deletions

View File

@ -17,7 +17,7 @@ public final class AbsoluteMax {
} }
int absMax = numbers[0]; int absMax = numbers[0];
for (int i = 1; i < numbers.length; i++) { 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]; absMax = numbers[i];
} }
} }

View File

@ -19,4 +19,12 @@ public class AbsoluteMaxTest {
void testGetMaxValueWithNoArguments() { void testGetMaxValueWithNoArguments() {
assertThrows(IllegalArgumentException.class, AbsoluteMax::getMaxValue); 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));
}
} }